我有一个组件库,我正在使用Jest和react-testing-library编写单元测试。基于某些道具或事件,我想验证某些元素没有被渲染。
如果未找到元素,则在react-testing-library中抛出和错误,导致在expect函数触发之前测试失败。
如何使用react-testing-library测试不存在的东西?
我有一个组件库,我正在使用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();
});
});
其他回答
另一个解决方案:您也可以使用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');
使用queryBy / queryAllBy。
如您所说,如果没有找到任何东西,getBy*和getAllBy*将抛出一个错误。
然而,等效的方法queryBy*和queryAllBy*返回null或[]:
queryBy queryBy*查询返回查询的第一个匹配节点,如果没有匹配的元素则返回null。这对于断言不存在的元素非常有用。如果找到多个匹配项,则会抛出(使用queryAllBy代替)。 queryAllBy queryAllBy*查询返回一个包含所有匹配节点的数组,如果没有元素匹配则返回一个空数组([])。
https://testing-library.com/docs/dom-testing-library/api-queries#queryby
因此,对于您提到的特定两个查询,您将使用queryByText和querybytestd,但它们适用于所有查询,而不仅仅是这两个查询。
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);
});
// 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();