66

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.
Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
strider
  • 5,674
  • 4
  • 24
  • 29
  • 3
    This a hack rather than an answer. You can try `expect(''+obj).toEqual(''+foo(2))`. It compares the function string content rather than the function itself. – Malice Aug 12 '17 at 03:09
  • @Malice thats not bad, though the second test is closer to my use case, where I have the anon fn assigned to a property in the object I want to compare. Your method could work as the builtin method of choice within `.toEqual` for checking this type of equality – strider Aug 12 '17 at 23:12
  • ...but unfortunate the equality is not entirely accurate, as `''+foo(1) === ''+foo(2)` evaluates to true – strider Aug 12 '17 at 23:20

1 Answers1

104

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.

Wiktor Czajkowski
  • 1,623
  • 1
  • 14
  • 20
  • 19
    thx for the answer, your alternative way is enough for my tests! `expect(result).toEqual({ getFooData: expect.any(Function), foo: 'some foo string' })` – teberl Mar 14 '18 at 15:19