Unit testing atomWithQuery
#2616
Replies: 1 comment
-
I'm not sure if or how you can set the atom value for queries in tests, but I wouldn't recommend it anyway. You get less confidence that your code is actually working if you mock the atom value and skip the query. I would recommend to actually run the query in your tests and instead mock the API endpoint, either via axios (e.g. axios mock adapter) or a library like MSW. Alternatively, you can set the query data via query client. Create the query client in your tests, configure a higher default stale time and call |
Beta Was this translation helpful? Give feedback.
-
What is the recommended approach to unit testing
atomWithQuery
?For example, let's say that I have an atom like the one below:
Then, I use it in a component like this:
Additionally, let's say I have a custom hook that uses the value for some operation:
How would I go about testing the component and the custom hook with this read-only
atomWithQuery
?I tried to initially hydrate the atoms in the test suite but it did not seem to work. After that, I tried to create a store for the test suite where I set the atom value, but I got errors while running the tests.
I was able to get the tests to pass by changing the atom to a writeable atom like this:
Then in my tests I just set the atom to a mock value. This seems like an anti-pattern though, and would not scale well since I'd have to do this for every atom in the application. Not to mention that there are additional properties/methods on the result object returned from Tanstack. Just doesn't seem like a good solution, even though it technically works for testing.
Are there examples of unit tests for
atomWithQuery
that I can reference?Beta Was this translation helpful? Give feedback.
All reactions