React 测试库:如何显式重用渲染组件而不删除自动清理

Ale*_*rff 3 react-testing-library

  1. RTLib有自动清理功能,我想保留它。
  2. 但在某些情况下,我想以这种方式重用组件的渲染结果(简化测试)
describe('some set of related functionality', () => {
    const onSelect = jest.fn();
    const Wrapper = render(
      <MyComponent onSelect={onSelect)} />
    );

    afterEach(() => {
      onSelect.mockReset();
    });

    it('tests something', async () => {
      userEvent.click(await Wrapper.findByText('some-text'));
      expect(onSelect).toBeCalledWith('something');
    });

    it('also tests something on the same component very related to closest describe block', async () => {
      userEvent.click(await Wrapper.findByText('some-other-text'));
      expect(onSelect).toBeCalledWith('some-other-thing');
    });
});
Run Code Online (Sandbox Code Playgroud)

所以这里的想法是在一些测试之间重用包装器并查询该包装器而不是在 global 中清理的全局屏幕afterEach

我喜欢默认行为,但我认为在某些测试之间重用包装器可能很有用,例如加快某些测试速度或缩短测试时间。

目前的替代方案是在一条语句中编写许多断言(实际上是许多测试)it。例如它可以是这样的

it('tests some set of related functionality', () => {
    const onSelect = jest.fn();
    render(<MyComponent onSelect={onSelect)} />);

    // tests something
    userEvent.click(await Wrapper.findByText('some-text'));
    expect(onSelect).toBeCalledWith('something');

    // have to do it manually now
    onSelect.mockReset();

    // also tests something on the same component
    userEvent.click(await Wrapper.findByText('some-other-text'));
    expect(onSelect).toBeCalledWith('some-other-thing');
});
Run Code Online (Sandbox Code Playgroud)

这里的动机是:

  1. 测试速度
  2. 能够编写一系列测试,其中每个步骤本身就是一个测试用例,无需重复渲染代码和先前的步骤(即用户交互)即可达到特定的组件状态。

有什么办法可以实现这一点吗?

ken*_*dds 7

这个问题有点主观,但作为您正在使用的库的创建者,您可能会对我的观点感兴趣(特别是因为您通过电子邮件向我发送了此链接)

您提到的替代方法是推荐的方法。请阅读编写更少、更长的测试来了解更多内容。

另外,我注意到你所说的返回值render Wrapper是酶的旧残渣,我建议也避免这种情况。请阅读React 测试库的常见错误了解更多相关信息。

我希望这有帮助。