Within the testing library framework, you can write a test like this where the expectation is implied, i.e. the test will fail as a result of the getByText
method throwing if it can't find the given text:
it('sets some text', () => {
...
screen.getByText('someText');
});
Although this works, this is relying on the implementation detail of testing library. So, I'm curious to know if this is accepted, or whether an explicit expect
should be in place, like
it('sets some text', () => {
...
expect(screen.getByText('someText')).toBeInTheDocument();
});
It's a matter of preference, really, so using get*
as an assertion isn't really wrong, but it's less explicit and can make it difficult to understand what is really being tested in some cases.
However, it is the opinion of the library's creator that using get*
variants as assertions is a bad pattern, as it is specifically listed in his article, Common Mistakes with React Testing Library:
...many people skip the assertion. This really is fine honestly, but I personally normally keep the assertion in there just to communicate to readers of the code that it's not just an old query hanging around after a refactor but that I'm explicitly asserting that it exists.
Generally, if you want to assert that something exists, make that assertion explicit.