Skip to content

Instantly share code, notes, and snippets.

@tejendra
Created September 30, 2021 16:22
Show Gist options
  • Save tejendra/12cc775750ae156dad4d48b2e6d2538b to your computer and use it in GitHub Desktop.
Save tejendra/12cc775750ae156dad4d48b2e6d2538b to your computer and use it in GitHub Desktop.
How to clear RTK Query cache in tests between requests when using Mock Service Worker and Jest
import React from 'react';
import { rest } from 'msw';
import userEvent from '@testing-library/user-event';
import { render, screen } from '../testUtils';
import ItemsPage from '../pages/Items';
import server from '../mocks/server';
describe('given Items Page', () => {
test('fetches items from API on page load', async () => {
render(<ItemsPage />);
const rows = await screen.findAllByText(/items_/);
expect(rows).toHaveLength(4);
});
test('renders no items message when API returns 0 results', async () => {
server.use(rest.get('/items', (req, res, ctx) => res(ctx.json([]))));
render(<ItemsPage />);
const noItemsText = await screen.findByText(
/There are no items/
);
expect(noItemsText).toBeInTheDocument();
});
test('renders error message if API fails on page load', async () => {
server.use(
rest.get('/items', (req, res, ctx) =>
res(ctx.status(500), ctx.json({ message: 'Internal Server Error' }))
)
);
render(<ItemsPage />);
const errorText = await screen.findByText(
/There was an error fetching items/
);
expect(errorText).toBeInTheDocument();
});
});
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const myApi = createApi({
reducerPath: 'myApi',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (builder) => ({
getAllItems: builder.query({
query: () => '/items'
})
})
});
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetAllItemsQuery } = myApi;
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';
import server from './mocks/server'; // set up msw server
import store from './store';
import { myApi } from './services';
beforeAll(() => server.listen());
afterEach(() => {
server.resetHandlers();
// This is the solution to clear RTK Query cache after each test
store.dispatch(myApi.util.resetApiState());
});
afterAll(() => server.close());
import { configureStore } from '@reduxjs/toolkit';
import { setupListeners } from '@reduxjs/toolkit/query/react';
import { myApi } from './services';
const store = configureStore({
reducer: {
[myApi.reducerPath]: myApi.reducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(myApi.middleware),
});
// optional, but required for refetchOnFocus/refetchOnReconnect behaviors
// see `setupListeners` docs - takes an optional callback as the 2nd arg for customization
setupListeners(store.dispatch);
export default store;
import React from 'react';
import { render } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './store';
import './locale';
// eslint-disable-next-line react/prop-types
const AllTheProviders = ({ children }) => {
return (
<MemoryRouter initialEntries={['/home']}>
<Provider store={store}>
{children}
</Provider>
</MemoryRouter>
);
};
const customRender = (ui, options) => {
return render(ui, { wrapper: AllTheProviders, ...options });
};
export * from '@testing-library/react';
export { customRender as render };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment