How to expect a getByText to be false in react testing library?
Asked Answered
L

3

15

I am using Jest and the React testing library to test a component.

I am trying to test a modal and I have a weird issue that I am facing. When I try to get by text the "Modal Title" before firing the event I get en error because the "Modal Title" does not exist in the rendered document. If I try to look for the "Modal Title" after firing the "Open Modal" button it works. But I would like to test as well that the modal does not exist before the triger event. So I decided to expect the "Modal Title" to be false but that doesn't work. So far I have tried the toBe(false), toBeFalsy(), toBeNull() and even tried to see if the lenght is 0 but nothing of the mentioned work. How can I solve this.

it('Test Modal', () => {
    
    const { getByText } = render(<TestApp />);
   
    expect(getByText('Modal Title')).toBe(false);
    fireEvent.click(getByText('Open Modal'));
    expect(getByText('Modal Title')).toBeTruthy();
})
Lacee answered 11/3, 2021 at 19:54 Comment(4)
expect(queryByText(...)).not.toBeInDocument()?Tenotomy
Does this answer your question? How do you test for the non-existence of an element using jest and react-testing-library?Tenotomy
@Tenotomy Nope. Neither one of the two work.Lacee
Please give a minimal reproducible example illustrating how precisely they don't work.Tenotomy
H
25

You can also expect getByText to throw an error like so:

expect(() => screen.getByText('Modal title')).toThrow();

(Note the () => notation at the start.)

Heptateuch answered 18/3, 2021 at 21:59 Comment(0)
H
8

You can also use the queryByText as this will provide a way to check if the returned value is null and requires less code. The following is one example:

const SectionOne = screen.queryByText('Section 1')
expect(SectionOne).toBeNull()
Helicoid answered 16/2, 2022 at 4:50 Comment(1)
This is a much cleaner way than the accepted answer. Thank you.Knorring
H
1

Another good approach would be to wait for your open modal, something like:

describe('modal component', () => {
  test('should not be rendered', () => {
    render(<TestApp />);
    expect(screen.getByText('Modal Title')).not.toBeInTheDocument();
  });

  test('should be rendered', async () => {
    render(<TestApp />);
    fireEvent.click(screen.getByText('Open Modal'));
    expect(await screen.findByText('Modal Title')).toBeInTheDocument();
  });
});

findBy methods are a combination of getBy queries and waitFor.

Hamforrd answered 11/3, 2021 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.