-
We have some reducers in our app that is listening to query actions in order to update some shared state.
How could I go about testing this? In general we have a policy to always test reducer logic so it would be good to be able to test stuff like this as well. Tried something like this, but doesnt work:
I guess the main question is, how do we manually invoke the pending and fulfilled actions that belong to a query or mutation? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
Either mock the api and actually fire the query, or export the action in the devtools and copy-paste it into your test & dispatch it. It's just a plain object after all. |
Beta Was this translation helpful? Give feedback.
-
Thanks. Actually firing the query probably doesn't let me test the "pending" reducer change in isolation? Good tip to export from dev tools though, copying that worked. I would perhaps hope there is a way to create this action object using RTK tho, so that I don't have to manually maintain these. Same way I can with createAsyncThunk pending/fulfilled/rejected actions.
|
Beta Was this translation helpful? Give feedback.
-
I see your point. We surely don't want to trigger internal rtk query actions either, but perhaps some type of testing utility could be created for this. We are used to doing fine-grained testing of reducer logic, and as mentioned I dont see how running the full query will let me intercept and test the "pending" state. I guess I could assert while somehow delaying the mocked response? Perhaps you have some examples you could point me to to show how you prefer testing these things? |
Beta Was this translation helpful? Give feedback.
-
Really, handling the fact that you are using RTK Query at all as an implementation detail. Render your component, check that it renders the loading state and then that it enters the final result state. Just do clicks on UI elements and assert on changes in the UI. If you go much deeper into unit tests, from my experience the tests start resembling the code that is being tested instead of the actual use case more and more. Of course our tests are only "how do you test the library" tests, but a few of them render full components and assert how those look, too: https://github.com/reduxjs/redux-toolkit/tree/master/packages/toolkit/src/query/tests For better examples, probably read the documentation of React Testing Library. If you write the tests that way, it wouldn't really matter if you use RTK Query, React Query or something home-brewed. |
Beta Was this translation helpful? Give feedback.
Either mock the api and actually fire the query, or export the action in the devtools and copy-paste it into your test & dispatch it. It's just a plain object after all.