反应测试库 |无法在 describe 方法中将测试拆分为更小的块

react-testing-library | Cannot Split Test into smaller chunks inside describe method

我正在学习使用 react-testing-library

对 React 组件进行单元测试

然而,当我打算在 describe() 函数内将测试分成更小的块时,我的组件呈现正确。测试失败,原因如下。

目前只有一个或另一个test()通过,但不能同时通过

import React from 'react'
import 'react-testing-library/cleanup-after-each'
import { render, fireEvent } from 'react-testing-library'
import Quantity from '../components/Quantity'

describe('Quantity Component', () => {
  const { container, getByTestId } = render(<Quantity />)

// first test
  test('checks that quantity is never 0', () => {
    expect(getByTestId('quantity')).not.toBe('0')
  })

// second test
  test('checks for the initial product quantity count', () => {
    expect(getByTestId('quantity')).toHaveTextContent('1')

    fireEvent.click(getByTestId('increment'))
    expect(getByTestId('quantity')).toHaveTextContent('2')
  })
})

当尝试 运行 两者都测试时出现错误: Unable to find an element by: [data-testid="quantity"]

[data-testid="quantity"] 只是我在所需的 JSX 标记中传递的一个属性。

当运行只第一个或第二个测试而不是同时两个时测试通过。

我在这里错过了什么?

单元测试中严禁交叉污染。

问题是每个 Quantity Component 套件只进行一次设置,而每次测试都应该进行一次。这就是 beforeEach 的用途:

describe('Quantity Component', () => {
  let container, getByTestId;

  beforeEach(() => {
    ({ container, getByTestId } = render(<Quantity />));
  });
  ...

您还需要使用 afterEach 清理。

describe('your tests', () => {
  afterEach(cleanup);
  beforeEach(() => ({container, getById} = render(<Quantity />))

  it('does something', () => {
    expect(getByTestId('quantity')).toHaveTextContent(0);
  }
}

我建议您在 it 子句中调用 render,它使测试更易于管理:

describe('Quantity Component', () => {  
  test('checks that quantity is never 0', () => {
    const { container, getByTestId } = render(<Quantity />)
    expect(getByTestId('quantity')).not.toBe('0')
  })

  test('checks for the initial product quantity count', () => {
    const { container, getByTestId } = render(<Quantity />)
    expect(getByTestId('quantity')).toHaveTextContent('1')

    fireEvent.click(getByTestId('increment'))
    expect(getByTestId('quantity')).toHaveTextContent('2')
  })
})

额外的好处是,如果出于某种原因您的测试之一需要 运行 使用不同的道具,您可以使用此设置更轻松地做到这一点。