React-query: unit testing at odds with queryCache

Created on 6 May 2020  路  5Comments  路  Source: tannerlinsley/react-query

I'm having trouble working out the best way to test using react-query. I've looked at #113 but it doesn't solve my issues.

I've got a pretty good DI pattern for the actual fetching of data so that's not an issue. The issue I have is the queryCache persisting between tests. I can explicitly clear the cache before/after each test, but that doesn't help if you've got multiple async tests running in parallel.

Rather than importing a global queryCache, would it be helpful to store it in a react context, and then in your tests you can pass in a fresh cache for each test i.e.

mount(
  <QueryCacheProvider>
    <MyComponent/>
  <QueryCacheProvider>
)

or add it to the existing config provider.

The other issue I have is that my test runner (mocha) is hanging forever after the tests have run. I assume this is because of some internal timeouts/intervals/evenListeners or something. Am I missing some obvious way to stop them?

An example of an extremely simple test that's both failing and hanging:

      const Sink = createSink(() => {
        useAccount('foo'); // useAccount just calls useQuery
        expect(mockApiCall.called).to.be.true;
      });

      mount(
        <Wrapper>
          <Sink/>
        </Wrapper>
      );

(the reason it's failing is because a previous test has already called the useQuery hook and cached the response, if I ran a single test in isolation, it passes)

I think my bottom line of all this is I think react-query could do with some official ways to make unit testing easier (and keeping things isolated)

tests

Most helpful comment

thanks for raising this - your suggestion to clear the cache is sufficient for me
beforeEach(queryCache.clear)

would be great if was built-in

All 5 comments

you can ignore the "hanging" part, I forgot you have to manually unmount enzyme-mounted components :facepalm:

please ignore my ignore statement as my tests are still hanging intermittently :disappointed:

thanks for raising this - your suggestion to clear the cache is sufficient for me
beforeEach(queryCache.clear)

would be great if was built-in

@KerrGrah how do you get access to queryCache from inside your test? As in how do I import it?

@iamtekeste
import { queryCache } from 'react-query' :)

@iamtekeste
import { queryCache } from 'react-query' :)

I can't believe it was that easy! Thank you.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alveshelio picture alveshelio  路  6Comments

the133448 picture the133448  路  4Comments

lgenzelis picture lgenzelis  路  4Comments

ivowork picture ivowork  路  5Comments

oukayuka picture oukayuka  路  4Comments