Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
})
like image 437
TMLS_123 Avatar asked Dec 12 '25 02:12

TMLS_123


2 Answers

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

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

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

like image 106
Marcus Avatar answered Dec 14 '25 00:12

Marcus


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()
like image 25
Jason Rice Avatar answered Dec 13 '25 23:12

Jason Rice