@testing-library/react
provides several methods for querying rendered elements including getBy*
queries which will throw an error if the element is not found.
How should I handle this in my test when I just want to test that there rendered elements are on screen.
When the getBy
throws an error if element is not found there is no need to assert that expect(element).toBeInTheDocument()
but then I have a test without assertion.
Should I use a dummy assertion like expect(1).toBe(1)
or whats the best practice here?
Example:
describe("MyComponent", () => {
// Render helper
function renderer(props) {
const result = render(<MyComponent {...props} />);
// Will throw error when element with text "My element" is not found
const element = screen.getByText("My element");
return {...result, element);
}
it("renders with my element", () => {
const {element} = renderer({});
// Redundant, will always pass when reaching this point
expect(element).toBeInTheDocument();
});
// Has same effect but does not use assertion
it("renders with my element w/o assertion", () => {
renderer({});
// expect(1).toBe(1); // When using dummy assertion jest wont complain
});
});