首页 > 解决方案 > 用 jest 和 react-testing-library 测试反应上下文

问题描述

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

我在组件中放置了一个控制台日志,并且在创建上下文和创建组件(它应该接收上下文作为参数)之间放置一个控制台日志。由于某种原因,这导致组件中的 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 />)

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

标签: reactjsunit-testingjestjsreact-hooksreact-context

解决方案


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

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

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

而且我只是传递了authenticationInfos里面的内容,而不是 prop 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"
    // );
  });
});

推荐阅读