简体   繁体   English

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

[英]Testing anonymous function equality with Jest

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.

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 , eg在这种情况下,如果不重写逻辑以使用命名函数,除了在 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.bar is any function , using expect.any(Function) :或者,您可以使用expect.any(Function)检查obj.bar是否为any function

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

which might actually make more sense depending on the context of the test.根据测试的上下文,这实际上可能更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM