如果我 运行 乘法测试,getByText 会失败,但如果我 运行 单独测试,它会起作用

getByText fails if I run multiply tests but it works if I run separately

我有以下两个测试声明如下:

describe('Cart test', () => {
  ...
  const { getByTestId, getByText } = render(<CartTest items={items} />);
  ...
  test('Adding items to cart.', () => {
 // empty nothing inse
  });
  test('Removing items from cart.', () => {
    getByText('Empty cart'); // it contains only this I delete all just doesn't work
  });
}

如果我 运行 开玩笑 -t 'Removing' 测试 运行 就好了。 如果我 运行 开玩笑说 useCar(这是文件的名称),我会得到错误 TestingLibraryElementError: Unable to find an element with the text: Empty cart. 我是测试新手 我很确定它很容易修复。为什么如果我 运行 单独测试它 运行 就好了,但是如果我 运行 两个测试它都找不到那个元素?

再见,在这种情况下我总是做的是将组件的渲染放入每个测试中。喜欢:

describe('Cart test', () => {
...
test('Adding items to cart.', () => {
// empty nothing inse
});
test('Removing items from cart.', () => {
  const { getByTestId, getByText } = render(<CartTest items={items} />);
  getByText('Empty cart');
});
}

或者使用 beforeEach 函数,例如:

beforeEach(() => {
 const { getByText } = render(<CartTest items={items} />);

});