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

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

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


当前回答

queryByRole的默认行为是只查找一个元素。如果不是,则抛出错误。因此,如果您捕捉到一个错误,这意味着当前查询找到0个元素

expect(
   ()=>screen.getByRole('button')
).toThrow()

如果没有找到任何东西,getByRole返回'null'

 expect(screen.queryByRole('button')).toEqual((null))

findByRole是异步运行的,因此它返回一个Promise。如果它没有找到一个元素,它就拒绝承诺。如果你正在使用这个,你需要运行异步回调

test("testing", async () => {
  let nonExist = false;
  try {
    await screen.findByRole("button");
  } catch (error) {
    nonExist = true;
  }
  expect(nonExist).toEqual(true);
});
    

其他回答

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

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

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

另一个解决方案:您也可以使用try/catch块

expect.assertions(1)
try {
    // if the element is found, the following expect will fail the test
    expect(getByTestId('your-test-id')).not.toBeVisible();
} catch (error) {
    // otherwise, the expect will throw, and the following expect will pass the test
    expect(true).toBeTruthy();
}

当没有找到元素时,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); 
}