【问题标题】:Testing react context with jest and react-testing-library用 jest 和 react-testing-library 测试反应上下文
【发布时间】:2019-09-04 08:50:28
【问题描述】:

我正在尝试为我的component App.js 设置测试,该测试将context 作为道具并返回提供者。问题是当我尝试测试它时,我传递给它的上下文总是解析为未定义。

我在组件中放置了一个控制台日志,并且在创建上下文和创建组件之间放置了一个控制台日志(它应该接收上下文作为参数)。由于某种原因,这导致组件中的 console.log 首先出现。这可能是我得到上下文未定义的原因,因为它还没有被初始化。

// Component/Provider
const App = (props) => {
  const {children, context} = props;
  const {data, dispatch} = useReducer(reducer);
  console.log(context); //undefined and this console.log runs first
  return <context.Provider value={useCallback(dispatch)}>{children}</context.Provider>
}

在我的 test.js 中

import React, {useContext} from 'react';
import {render} from 'react-testing-library';
import {App} from './App';
const context = React.createContext();

function Provider(children) {
  console.log(context); //Is correct but runs second
  return <App Context={context}>{children}</App>;
}

const customRender = (ui, options) =>
  render(ui, { wrapper: Provider, ...options });

const Consumer = () => {
  const dispatch = useContext(context);
  returns <Button onClick={dispatch({type: 'Do something'})}>Whatever</Button/>;
}
customRender(<Consumer />)

我应该能够将Context 传递到我的组件中以创建提供程序,但它始终未定义。

【问题讨论】:

  • 我相信你已经发现你的组件需要context prop但是Context被传递了。外壳很重要。

标签: reactjs unit-testing jestjs react-hooks react-context


【解决方案1】:

也许这是一个错字,但你的文件真的叫test.js吗? 如果是这样,您需要将其更改为 .jsx,因为您在测试中使用 JSX(例如在 Provider 组件中)。

【讨论】:

    【解决方案2】:

    在找出如何继续之前,我被卡住了一会儿。我的问题是我没有为上下文创建正确的形状:我给了它一些道具,但不是在我的真实上下文中传递的那个。所以组件无法浏览那个新形状。

    这是我的产品形状(非测试)

    export default React.createContext({
      authenticationInfos: {
        isAuthenticated: false,
        user: {
          id: "",
          email: "",
          roles: []
        },
        customer: {
          id: "",
          prenom: "",
          nom: "",
          tel: "",
          adress: "",
          postalCode: "",
          town: "",
          sellRequests: []
        }
      },
      setAuthenticationInfos: value => {}
    });
    

    我只是传递了 authenticationInfos 内部的内容,而不是 authenticationInfos 本身的属性,而且我也忘记了 setAuthenticationInfos 属性。

    这是我使用上下文挂钩的测试组件:

    react-testing-library 文档中的函数

    const customRender = (ui, { providerProps, ...renderOptions }) => {
      return render(
        <AuthContext.Provider value={providerProps}>{ui}</AuthContext.Provider>,
        renderOptions
      );
    };
    
    describe("<ConnectModal>", () => {
      test("should be able to access auth context", () => {
        const providerProps = {
          authenticationInfos: {
            isAuthenticated: false,
            user: {
              id: "",
              email: "",
              roles: [],
            },
            customer: {
              id: "",
              prenom: "",
              nom: "",
              tel: "",
              adress: "",
              postalCode: "",
              town: "",
              sellRequests: [],
            },
            shop: {
              appToken: 54,
            },
          },
          setAuthenticationInfos: (value) => {},
        };
        customRender(<MKMConnectModal />, { providerProps });
        // expect(screen.getByText(/^My Name Is:/)).toHaveTextContent(
        //   "My Name Is: C3P0"
        // );
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 2021-02-11
      • 2020-03-22
      • 2020-05-14
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多