Javascript 用 Jest 测试匿名函数的相等性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45644098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:08:08  来源:igfitidea点击:

Testing anonymous function equality with Jest

javascriptnode.jsunit-testingjestjsequality

提问by strider

Is there a way to test anonymous function equality with jest@20?

有没有办法用 来测试匿名函数的相等性jest@20

I am trying to pass a test similar to:

我正在尝试通过类似于以下内容的测试:

const foo = i => j => {return i*j}
const bar = () => {baz:foo(2), boz:1}

describe('Test anonymous function equality',()=>{

    it('+++ foo', () => {
        const obj = foo(2)
        expect(obj).toBe(foo(2))
    });

    it('+++ bar', () => {
        const obj = bar()
        expect(obj).toEqual({baz:foo(2), boz:1})
    });    
});

which currently yields:

目前产生:

  ● >>>Test anonymous function equality ? +++ foo

    expect(received).toBe(expected)

    Expected value to be (using ===):
      [Function anonymous]
    Received:
      [Function anonymous]

    Difference:

    Compared values have no visual difference.

  ● >>>Test anonymous function equality ? +++ bar

    expect(received).toBe(expected)

    Expected value to be (using ===):
      {baz: [Function anonymous], boz:1}
    Received:
      {baz: [Function anonymous], boz:1}

    Difference:

    Compared values have no visual difference.

回答by Wiktor Czajkowski

In such situation, without rewriting your logic to use named functions, you don't really have another choice other than declaring the function before the test, e.g.

在这种情况下,如果不重写逻辑以使用命名函数,除了在 test 之前声明函数之外,您真的没有其他选择,例如

const foo = i => j => i * j
const foo2 = foo(2)
const bar = () => ({ baz: foo2, boz: 1 })

describe('Test anonymous function equality', () => {
  it('+++ bar', () => {
    const obj = bar()
    expect(obj).toEqual({ baz: foo2, boz: 1 })
  });    
});

Alternatively, you can check whether obj.baris anyfunction, using expect.any(Function):

或者,您可以使用以下方法检查是否obj.bar任何函数expect.any(Function)

expect(obj).toEqual({ baz: expect.any(Function), boz: 1 })

which might actually make more sense depending on the context of the test.

根据测试的上下文,这实际上可能更有意义。