I'm making unit tests for React components using apollo hooks (useQuery
, useMutation
), and in the tests I mock the actual queries with apollo's MockedProvider
. The problem is that sometimes, my mock doesn't match the query actually made by the component (either a typo when creating the mock, or the component evolves and changes some query variables). When this happens, MockedProvided
returns a NetworkError to the component. However in the test suite, no warning is displayed. This is frustrating, because sometimes my components do nothing with the error returned by useQuery
. This cause my tests, which used to pass, to suddenly fail silently, and gives me a hard time to find the cause.
This is an example of component using useQuery
:
import React from 'react';
import {gql} from 'apollo-boost';
import {useQuery} from '@apollo/react-hooks';
export const gqlArticle = gql`
query Article($id: ID){
article(id: $id){
title
content
}
}
`;
export function MyArticleComponent(props) {
const {data} = useQuery(gqlArticle, {
variables: {
id: 5
}
});
if (data) {
return (
<div className="article">
<h1>{data.article.title}</h1>
<p>{data.article.content}</p>
</div>
);
} else {
return null;
}
}
And this is a unit test, in which I made a mistake, because the variables object for the mock is {id: 6}
instead of {id: 5}
which will be requested by the component.
it('the missing mock fails silently, which makes it hard to debug', async () => {
let gqlMocks = [{
request:{
query: gqlArticle,
variables: {
/* Here, the component calls with {"id": 5}, so the mock won't work */
"id": 6,
}
},
result: {
"data": {
"article": {
"title": "This is an article",
"content": "It talks about many things",
"__typename": "Article"
}
}
}
}];
const {container, findByText} = render(
<MockedProvider mocks={gqlMocks}>
<MyArticleComponent />
</MockedProvider>
);
/*
* The test will fail here, because the mock doesn't match the request made by MyArticleComponent, which
* in turns renders nothing. However, no explicit warning or error is displayed by default on the console,
* which makes it hard to debug
*/
let titleElement = await findByText("This is an article");
expect(titleElement).toBeDefined();
});
How can I display an explicit warning in the console ?