1

我在使用 Jest 和 React-test-renderer 测试反应钩子应用程序时遇到问题。当我将 useQuery 放在 react hooks 上下文文件中时定义的问题。

我在这个 apollo 文档https://www.apollographql.com/docs/react/development-testing/testing/之后有一个类似的文件,但在 react hooks 上下文文件中调用 useQuery 只是不同。

CatContext.js

import React, {createContext} from 'react';
import { GET_ALL_CATS } from 'graphqlquery/Queries';
import { useQuery } from '@apollo/client';

export const CatContext = createContext();

export default function CatContextProvider(props) {
    const { loading, error, data } = useQuery(GET_ALL_CATS);
        
    return (
        <CatContext.Provider value={{loading,error,data}}>
            {props.children}
        </CatContext.Provider>
    );
}

应用程序.js

export function CatList() {
    const {loading,error,data} = useContext(CatContext);
    if(loading) return <div>Loading...</div>;
    if(error) return <div>Error...</div>;
    return (
        <div>
            <div>
                    {data.cat.name} is a {data.cat.breed}
            </div>
        </div>
    );
}

应用程序.test.js

import React from 'react';
import { MockedProvider } from '@apollo/client/testing';
import TestRenderer from 'react-test-renderer';
import "regenerator-runtime/runtime";
import { CatList } from 'components/CatList';
import { GET_ALL_CATS } from 'graphqlquery/Queries';

const mocks = [
    {
      request: {
        query: GET_ALL_CATS,
      },
      result: {
        data: {
            cat: { id: '1', name: 'Buck', breed: 'bulldog' },
        }
      }
    }
  ]

  it('renders without error', () => {
    const component = TestRenderer.create(
      <MockedProvider mocks={mocks} addTypename={false}>
        <CatList  />
      </MockedProvider>,
    );
  
    const tree = component.toJSON();
    expect(tree.children).toContain('Loading...');
  });

如果我在里面调用 useQuery 则问题不存在App.js,但是当我在里面调用 useQuery 时CatContext,它会提供一个错误:TypeError: Cannot read property 'loading' of undefined.

任何想法为什么loading我调用的 useQueryCatContext.js是未定义的?以及如何解决?

4

0 回答 0