描述方法只能通过 1 次测试,除非一次又一次地重新渲染每个组件

Describe method can only pass with 1 test unless re-rendering each component again and again

我想弄清楚为什么只要描述块包含超过 1 个测试,我的测试(仅在 运行 时通过)就会失败。以这个例子为例,我从我的真实代码中提取并简化了它:

describe('Create Account Form', () => {
  const {container} = render(<CreateAccountForm />);
  const email = container.querySelector('input[name="email"]');
  const password1 = container.querySelector('input[name="password1"]');

  it('Should render all fields', () => {
    allInputs.forEach((input) => {
      expect(input).toBeInTheDocument();
    });
  });

  it('Another test', () => {
    expect(email).toBeInTheDocument(); // fails
  });
});

第二个测试失败,但只有在注释掉第一个测试时才能通过,或者在测试中再次重新渲染容器,如下所示:

  it('Another test', () => {
    const {container} = render(<CreateAccountForm />);
    const email = container.querySelector('input[name="email"]');
    expect(email).toBeInTheDocument(); // passes
  });

为什么会发生这种情况?我宁愿不必重新渲染容器并在每个测试块中声明新变量。

谢谢

RTL 将卸载在 afterEach 挂钩中使用渲染挂载的 React 树。参见 cleanup

Please note that this is done automatically if the testing framework you're using supports the afterEach global and it is injected to your testing environment (like mocha, Jest, and Jasmine).

render 代码移动到 beforeEach 或单独的测试用例中。这样我们就可以在每个测试用例之前创建反应树。将测试用例彼此隔离,使用自己的测试数据而不影响其余部分。

例如

index.tsx:

import React from 'react';

export function Example() {
  return (
    <div>
      <input name="email" />
      <input name="password1" />
    </div>
  );
}

index.test.tsx:

import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import React from 'react';
import { Example } from './';

describe('70753645', () => {
  let email, password1, allInputs;
  beforeEach(() => {
    const { container } = render(<Example />);
    email = container.querySelector('input[name="email"]');
    password1 = container.querySelector('input[name="password1"]');
    allInputs = container.querySelectorAll('input');
  });

  it('Should render all fields', () => {
    allInputs.forEach((input) => {
      expect(input).toBeInTheDocument();
    });
  });

  it('Another test', () => {
    expect(email).toBeInTheDocument();
  });
});

测试结果:

 PASS  Whosebug/70753645/index.test.tsx (9.222 s)
  70753645
    ✓ Should render all fields (24 ms)
    ✓ Another test (3 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.717 s

包版本:

"@testing-library/react": "^11.2.2",
"jest": "^26.6.3",