Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  97] [ 2]  / answers: 1 / hits: 29424  / 4 Years ago, tue, june 16, 2020, 12:00:00

For example, I want to know what has been dispatched and the argument. The action creator is asynchronous, but I don't care about its implementation, I just want to know if the component dispatches the correct action creator with the correct argument. I've tried this approach:



store.dispatch = jest.fn()


But I can't get any useful information:



this



I've tried to solve the problem by this way:



expect(store.dispatch.mock.calls[0].toString()).toBe(requestArticles().toString())


But I don't know the argument and I'm sure, that there are a better way to do this. Also of note, I'm using react-testing-library, so I can't use wrapper.instance().props from Enzyme.


More From » reactjs

 Answers
9

You can mock the action file and check if the action has been called.



e.g. Lets say foo.action.js is the file which has the action being dispatched.



in the start of your test file before importing the component, you can mock the file as:



const yourActionMock = jest.fn();
jest.mock('<Path to the action file>/foo.action.js', () => ({
yourAction: yourActionMock
}));


now you can test the action called as:
expect(yourActionMock).toHaveBeenCalledWith(<args>)


[#50871] Monday, June 1, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katharinek

Total Points: 302
Total Questions: 105
Total Answers: 123

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
;