我有一个组件库,我正在使用Jest和react-testing-library编写单元测试。基于某些道具或事件,我想验证某些元素没有被渲染。

如果未找到元素,则在react-testing-library中抛出和错误,导致在expect函数触发之前测试失败。

如何使用react-testing-library测试不存在的东西?


当前回答

你必须使用querybytestd而不是getbytestd。

这里是一个代码示例,我想测试是否组件与“汽车”id不存在。

 describe('And there is no car', () => {
  it('Should not display car mark', () => {
    const props = {
      ...defaultProps,
      base: null,
    }
    const { queryByTestId } = render(
      <IntlProvider locale="fr" messages={fr}>
        <CarContainer{...props} />
      </IntlProvider>,
    );
    expect(queryByTestId(/car/)).toBeNull();
  });
});

其他回答

对我来说(如果你想使用getbytestd):

expect(() => getByTestId('time-label')).toThrow()
const submitButton = screen.queryByText('submit')
expect(submitButton).toBeNull() // it doesn't exist

expect(submitButton).not.toBeNull() // it exist

当没有找到元素时,getBy*将抛出一个错误,因此您可以检查它

expect(() => getByText('your text')).toThrow('Unable to find an element');

我最近为一个笑话黄瓜项目写了一个检查元素可见性的方法。

希望对大家有用。

public async checknotVisibility(page:Page,location:string) :Promise<void> 
{
    const element = await page.waitForSelector(location);
    expect(element).not.toBe(location); 
}
// check if modal can be open
const openModalBtn = await screen.findByTestId("open-modal-btn");
fireEvent.click(openModalBtn);

expect(
  await screen.findByTestId(`title-modal`)
).toBeInTheDocument();


// check if modal can be close
const closeModalBtn = await screen.findByTestId(
  "close-modal-btn"
);
fireEvent.click(closeModalBtn);

const sleep = (ms: number) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

await sleep(500);
expect(screen.queryByTestId("title-modal")).toBeNull();