'How can I test what variables an Apollo useQuery hook was called with using Enzyme?
I have a simple Apollo Query that I want to run. In some cases, it should pass in an optional argument set to true. In others, the argument will not be provided, and it should default to false.
I'm trying to set up a test in jest/enzyme that will confirm that it is running with the correct default variables, but I am having difficulty doing so. Here's what I have so far. Variable names are altered to protect privacy/company names.
The test file: import * as ApolloClient from '@apollo/client'; import { makeUseQuery } from '../../../../test/mocks/graphql';
import {useMyQuery} from './useMyQuery'
const querySpy = jest.spyOn(ApolloClient,'useQuery')
const defaultQuery = {
userKey: 'mock-user_key',
variableName: false
}
describe('useMyQuery()',()=>{
beforeEach(() => {
jest.clearAllMocks();
});
it('should default to variableName = false',()=>{
querySpy.mockReturnValueOnce(makeUseQuery());
useMyQuery()
expect(querySpy).toHaveBeenCalledWith(defaultQuery)
//Returns the arguments for the query as well as extra boilerplate Apollo data, such as alias, selectionSet, fetchPolicy, etc.
})
})
The hook that I'm attempting to test:
import { useQuery } from '@apollo/client';
import {useAuth} from '@company_name/auth'
import {
MyQuery,
MyQueryVariables,
} from '../__generated__/MyQuery';
import { FETCH_MY_QUERY } from '../MyQueryRoute.graphql';
export const useMyQuery = (myVariable?: boolean) => {
const { userKey } = useAuth();
return useQuery<MyQuery, MyQueryVariables>(
FETCH_MY_QUERY,
{
variables: {
userKey: userKey!,
myVartiable: myVariable ?? false,
},
skip: !userKey,
fetchPolicy: 'no-cache',
}
);
};
How can I modify my test so that it will check the value of myVariable and confirm if it is true or false? (the auth conditions are covered in other tests that are outside of my scope)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
