Go Back

SWR and testing with Storybook interactions

Posted: 

We recently picked up SWR in to help with our data fetching needs. So far it's been a great library and served our needs.

However, when it came to automated testing we were constantly getting failed tests in different contexts. Everything seemed to pass when I ran the Storybook locally in browser but when I sent it up to Chromatic, one of the tests would fail.

I decided to setup the Storybook test runner and ran that locally. The test that failed in Chromatic would pass but another one would fail. What!?

The issue was that SWR was being to good at it's job. It would cache results between stories so that our mocked data fetching using the msw Storybook addon would return the wrong results.

The answer was to wrap each story that uses SWR with a custom <SWRConfig> component using Storybook's decorator functionality.

decorators: [
(Story) => (
<SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>
<Story />
</SWRConfig>
),
],

Now mocking data is far more predictable and our tests pass!

Here is the documentation from SWR's site - Reset Cache Between Test Cases