简体   繁体   中英

How to test functions for equality when unit testing

I have the following code:

DeviceEventEmitter.addListener(eventName, () => { return 'myHandler' })

I am testing that DeviceEventEmitter is called with the following test:

DeviceEventEmitter.addListener = jest.fn();
expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(() => { return 'myHandler' });

However, the test fails with:

expect(received).toEqual(expected)

Expected value to equal:
  [Function anonymous]
Received:
  [Function anonymous]

It looks like it doesn't understand that the functions are the same.

So how can I make it detect when the functions are the same?

This will always return false because you're creating a new function as parameter for the toEqual function:

expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(() => { return 'myHandler' });

2 functions with the same body are still different. You have to keep the reference to the listener and then compare the reference:

var listener = () => { return 'myHandler' }
DeviceEventEmitter.addListener(eventName, listener)

DeviceEventEmitter.addListener = jest.fn();
expect(DeviceEventEmitter.addListener.mock.calls[0][1]).toEqual(listener);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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