“Cannot read property _location of null” when testing with Jest and react-testing-library #12107
Closed
Description
I am encountering this issue intermittently but regularly when testing my NextJS React application using Jest and react-testing-library. Tests are randomly failing with the error:
"Cannot read property _location of null"
This happens, I believe, because the Jest test process exits too quickly relative to what Apollo is doing, but I confess my understanding of this is a bit lacking.
I would appreciate any guidance on the issue and how I can resolve it! I have provided an example of how I am using Apollo as part of a custom render function in my tests.
Thanks in advance
Example:
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';
import { RenderOptions, render } from '@testing-library/react';
import { MemoryRouterProvider } from 'next-router-mock/MemoryRouterProvider';
import { ReactElement } from 'react';
const generateMockClient = () =>
new ApolloClient({
uri: process.env.NEXT_PUBLIC_GRAPHQL_API_URL,
cache: new InMemoryCache(),
defaultOptions: {
watchQuery: {
errorPolicy: 'ignore',
},
query: {
errorPolicy: 'all',
},
},
});
const AllTheProviders = ({ children }: { children: React.ReactNode }) => {
return (
<MemoryRouterProvider>
<ApolloProvider client={generateMockClient()}>{children}</ApolloProvider>
</MemoryRouterProvider>
);
};
const customRender = (ui: ReactElement, options?: Omit<RenderOptions, 'wrapper'>) => {
return render(ui, { wrapper: AllTheProviders, ...options });
};
export * from '@testing-library/react';
export { customRender as render };
and then run a test:
describe('Feature', () => {
it('does something', async () => {
render(<MyFeature />);
const text = screen.getByText('My text');
expect(text).toBeVisible();
});
});
Metadata
Assignees
Labels
No labels