There is a situation when some test ids should not be present in the DOM and it must be tested.
For example:
describe('MyModal', () => {
const testIds = [
'first-test',
'second-test',
'third-test'
];
it('should not render MyModal', () => {
const { getByTestId } = renderWithClientInstance(
<MyModal open={false} } />
);
testIds.forEach((testId) => expect(getByTestId(testId)).not.toBeInTheDocument());
});
});
But this test fails with the following error message:
TestingLibraryElementError: Unable to find an element by: [data-testid="first-test"]
How should it be written in order to check if those test ids aren't in the DOM?
The solution is to use queryByTestId instead of getByTestId because it doesn't fail when the queried element doesn't exist, instead, it returns either a value or null.
describe('MyModal', () => {
const testIds = [
'first-test',
'second-test',
'third-test'
];
it('should not queryByTestId MyModal', () => {
const { queryByTestId } = renderWithClientInstance(
<MyModal open={false} } />
);
testIds.forEach((testId) => expect(queryByTestId(testId)).toBeNull());
});
});