我正在使用apollo钩子(useQuery
,useMutation
)对React组件进行单元测试,在测试中,我使用apollo的MockedProvider
模拟了实际查询。问题在于,有时,我的模拟与组件实际进行的查询不匹配(创建模拟时出现错字,或者组件演变并更改了一些查询变量)。发生这种情况时,MockedProvided
将NetworkError返回到组件。但是,在测试套件中,不会显示警告。这令人沮丧,因为有时我的组件对useQuery
返回的错误不起作用。这使我曾经通过的测试突然无声地失败了,并给我带来了很难找到原因的麻烦。
这是使用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;
}
}
这是一个单元测试,我犯了一个错误,因为该模拟对象的变量对象是{id: 6}
而不是组件将要求的{id: 5}
。
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();
});
如何在控制台中显示明确的警告?
答案 0 :(得分:6)
我已经向阿波罗团队提交了Github issue,以建议一种内置方法。同时,这是我的自制解决方案。
这个想法是为MockedProvider
提供一个自定义的阿波罗链接。默认情况下,它使用通过给定模拟初始化的MockLink
。取而代之的是,我创建了一个自定义链接,该链接是由MockLink
组成的链,该链接的创建方式与MockedProvider
相同,随后是一个阿波罗错误链接,该链接拦截了可能是根据请求返回,并将其记录在控制台中。为此,我创建了一个自定义提供程序MyMockedProvider
。
MyMockedProvider.js
import React from 'react'; import {MockedProvider} from '@apollo/react-testing'; import {MockLink} from '@apollo/react-testing'; import {onError} from "apollo-link-error"; import {ApolloLink} from 'apollo-link'; export function MyMockedProvider(props) { let {mocks, ...otherProps} = props; let mockLink = new MockLink(mocks); let errorLoggingLink = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) graphQLErrors.map(({ message, locations, path }) => console.log( `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`, ), ); if (networkError) console.log(`[Network error]: ${networkError}`); }); let link = ApolloLink.from([errorLoggingLink, mockLink]); return <MockedProvider {...otherProps} link={link} />; }
MyArticleComponent.test.js
import React from 'react'; import {render, cleanup} from '@testing-library/react'; import {MyMockedProvider} from './MyMockedProvider'; import {MyArticleComponent, gqlArticle} from './MyArticleComponent'; afterEach(cleanup); it('logs MockedProvider warning about the missing mock to the console', 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" } } } }]; let consoleLogSpy = jest.spyOn(console, 'log'); const {container, findByText} = render( <MyMockedProvider mocks={gqlMocks}> <MyArticleComponent /> </MyMockedProvider> ); let expectedConsoleLog = '[Network error]: Error: No more mocked responses for the query: query Article($id: ID) {\n' + ' article(id: $id) {\n' + ' title\n' + ' content\n' + ' __typename\n' + ' }\n' + '}\n' + ', variables: {"id":5}'; await findByText('{"loading":false}'); expect(consoleLogSpy.mock.calls[0][0]).toEqual(expectedConsoleLog); });