apollo的MockedProvider并未明确警告缺少模拟内容

问题描述 投票:0回答:1

我正在使用apollo钩子(useQueryuseMutation)对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();
  });

如何在控制台中显示明确的警告?

reactjs unit-testing apollo react-apollo apollo-client
1个回答
0
投票

我已向阿波罗团队提交了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);
});

© www.soinside.com 2019 - 2024. All rights reserved.