Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

javascript - Testing anonymous function equality with Jest

Is there a way to test anonymous function equality with 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.
question from:https://stackoverflow.com/questions/45644098/testing-anonymous-function-equality-with-jest

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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(obj).toEqual({ baz: expect.any(Function), boz: 1 })

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...