8

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();
})
TMLS_123
  • 93
  • 1
  • 1
  • 6

3 Answers3

16

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

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

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

Marcus
  • 2,153
  • 2
  • 13
  • 21
2

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()
Jason Rice
  • 446
  • 5
  • 8
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.

AdriSolid
  • 2,570
  • 1
  • 7
  • 17