【问题标题】:Testing react component that is dependent on Stateful Context Providers chain in React Testing Library在 React 测试库中测试依赖于 Stateful Context Providers 链的 React 组件
【发布时间】:2020-10-18 06:50:45
【问题描述】:

我知道this,但这不是我的情况。

例子:

<AuthProvider>
  <SessionProvider>
    <AnotherProvider>
      <OneMoreProvider>
        <MyComponent />

所有这些提供程序实际上都是具有状态和效果的常规 React 组件,它们通过 GraphQL 获取一些数据并将这些数据作为“值”prop 传递给 MyContext.Provider 在 return 语句中。

这迫使我为所有这些提供程序中使用的模块创建大量模拟,只是为了在测试环境中呈现我自己的组件。

您有什么想法可以避免创建如此多的模拟吗?

【问题讨论】:

  • 您是否需要在测试中使用来自上下文提供者的变量?

标签: reactjs testing react-testing-library react-context use-context


【解决方案1】:

您可以创建一个带有自定义渲染函数的辅助测试库,该函数使用上下文包装您的组件,然后从那里导出所有反应测试库方法

- test/lib.jsx

import React from 'react';
import { render as reactRender } from '@testing-library/react';
export * from '@testing-library/react';

export const render = (MyComponent, options) => {
    return reactRender(
        <AuthProvider>
            <SessionProvider>
                <AnotherProvider>
                    <OneMoreProvider>
                        {MyComponent}
                    </OneMoreProvider>
                </AnotherProvider>
            </SessionProvider>
        </AuthProvider>,
        options
    )
}

然后使用这个helper lib来导入测试函数,而不是直接使用@testing-library/react


import { render } from 'test/lib'
import MyComponent from './MyComponent';

test("My component", () => {
    const { getByTestId, ... } = render(<MyComponent>);
    ...
});

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 2020-01-11
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 2021-11-09
    • 2022-08-10
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多