I got jest/enzyme tests working for my React component that calls out to GraphQL with Apollo's useQuery. Then I added a useMutation, and found that to get the component to show fresh data, I had to put a fetchPolicy on the useQuery. Works in the browser yay.
However, the jest tests will not show the mocked return from the useQuery any more. The useMutation doesn't seem to have messed anything up... All I have to do to get these tests to work is to comment out the fetchPolicy in the useQuery.
By "not working" I mean, the snapshot shows the component in its "loading" state, where without the fetchpolicy the snapshot showed that the component had resolved into the mocked-data-delivered-and-presented state.
Here's some of the component code:
import React from 'react';
import { useMutation, useQuery } from '@apollo/react-hooks';
const AlertSubscribersDialog = ({ alertRule }) => {
const { name } = alertRule;
const { data, error, loading } = useQuery(getSubscribers, {
variables: { name },
fetchPolicy: 'no-cache', // tests work if I comment this line out
});
Here's the test:
import React from 'react';
import { act } from 'react-dom/test-utils';
import { Provider, defaultTheme } from '@adobe/react-spectrum';
import { MockedProvider } from '@apollo/react-testing';
import { mount } from 'enzyme';
import AlertSubscribersDialog from './AlertSubscribersDialog';
import { getSubscribers } from 'components/alert/alert-management.graphql';
const mockFetch = {
subscribers: [ { email: '[email protected]' }, { email: '[email protected]' } ],
};
const mockHappyPath = [
{
request: {
query: getSubscribers,
variables: { name: 'error_foo_exceeded' },
},
result: { data: mockFetch },
},
];
const defaultProps = { alertRule: { name: 'error_foo_exceeded' } };
const render = props =>
mount(
<Provider theme={defaultTheme}>
<MockedProvider mocks={mockHappyPath} addTypename={false}>
<AlertSubscribersDialog {...defaultProps} {...props} />
</MockedProvider>
</Provider>,
);
describe('AlertSubscribersDialog', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
jest.useRealTimers();
});
it('should render Loading', () => {
const modal = render();
expect(modal).toMatchSnapshot();
});
it('should render with subscribers from GraphQL', () => {
const modal = render();
// MockedProvider needs time to give out the useQuery mock
act(() => {
jest.advanceTimersByTime(150);
});
modal.update();
expect(modal).toMatchSnapshot();
});
});
The versions I have are
"@apollo/client": "^3.6.9",
"@apollo/react-hooks": "^3.1.3",
"@apollo/react-testing": "^3.1.4",
"enzyme": "^3.11.0",
"jest": "^24.9.0",
"react": "^16.14.0",
"react-dom": "^16.12.0",