0

I have a react redux setup and react-testing-library for testing. My component dispatches an action with the required info as well as a callback on finish. But when trying to mock the dispatch call jest seems to compare references to functions rather than their bodies, which makes sense, but is there any way to deal with cases such as these at all?

// the store is mocked
store.dispatch = jest.fn();

...

expect(store.dispatch).toHaveBeenNthCalledWith(3, 
      postData({ data: 'abc' }, () => doSmth());

I get this slightly weird error:

Expected: {"callback": [Function anonymous], "payload": {"id": 2, "data": "abc" }, "type": "POST_DATA"}
    Received
           2: {"id": 2, "type": "POST_DATA"}
    ->     3
            @@ -1,7 +1,7 @@
              Object {
            -   "callback": [Function anonymous],
            +   "callback": [Function callback],

Any hints would be appreciated!

Edit: What am trying to assert on is an action object returned by action creator. In the code I've put callback code to fire after the action completes. so in the context postData({ data: 'abc' }, () => dosmth()) would return { type: POST_DATA, payload: { data: 'abc' }, callback: () => dosmth() }.

Whilst data equality can easily be asserted here, the function equality cannot.

Edit2: So my solution to wanting to ignore a part of an object was to use expect.objectContaining, to compare the part of the object I care about and the discard the callback part.

 // the callback in the `action` object is null, so just delete it 
 // from the object to assert on it
 const action = postData({ data: 'abc' });
 delete action.callback;
 expect(store.dispatch).toHaveBeenNthCalledWith(3,
   expect.objectContaining(action));
Grigory Bogush
  • 93
  • 1
  • 11

0 Answers0