如何通过React-Testing-Library和Jest测试基于UseContext使用自定义钩子的代码

问题描述

我已经创建了一个自定义上下文挂钩-我正在努力弄清楚如何在测试过程中将值传递给其提供程序。

我的钩子:

import React,{ createContext,useContext,useState } from 'react';

const Context = createContext({});

export const ConfigurationProvider = ({ children }) => {
  // Use State to keep the values
  const [configuration,setConfiguration] = useState({});

  // pass the value in provider and return
  return (
    <Context.Provider
      value={{
        configuration,setConfiguration,}}
    >
      {children}
    </Context.Provider>
  );
};

export const useConfigurationContext = () => useContext(Context);
export const { Consumer: ConfigurationConsumer } = Context;

在应用程序中的用法如下:

function App() {
  return (
    <ConfigurationProvider>
      <div className="app">
        <ComponentA />
      </div>
    </ConfigurationProvider>
  );
}

在ComponentA中:

const ComponentA = () => {
  // Get configuration
  const configuration = useConfigurationContext();

  return (
    <div>{JSON.stringify(configuration)}</div>
  )
}

一切正常-考虑到我正在从另一个组件调用setConfiguration并设置一个对象。现在进行测试:

import React,{ Component,createContext } from 'react';
import { render,waitFor } from '@testing-library/react';
import ComponentA from 'componentA';

const config = {
  propertyA: 'hello',};

test('renders the config',async () => {
  const ConfigurationContext = createContext();

  const { queryByText } = render(
    <ConfigurationContext.Provider value={config}>
      <ComponentA />
    </ConfigurationContext.Provider>
  );

  expect(queryByText('hello')).toBeInTheDocument();
});

这不起作用-我期望要发送的值将在div中呈现,但是上下文是一个空对象。我在做什么错了?

解决方法

多亏了Carle B. Navy,我才知道为什么它不起作用。对于其他人,两个人想知道我通过执行以下操作来解决该问题的方法:

在上下文挂钩中,我还更改了最后一行以导出提供程序:

export const { Consumer: ConfigConsumer,Provider: ConfigProvider } = Context;

然后在我的测试用例中,而不是创建新的上下文,而是在顶部导入ConfigProvider,然后:

const { queryByText } = render(
  <ConfigProvider value={config}>
    <ComponentA />
  </ConfigProvider>
);

感谢您帮助我解决了这个问题,希望对您有所帮助。