Jest & Testing Library

You,web developmenttestingreact

React

Wait for async state updates

Use await findBy* queries to wait for async state updates.

it('will wait for state updates and check DOM content', () => {
  const { findByText } = render(<Component />)
  const sentence = await findByText('I took a while to display')
  expect(sentence).toBeInTheDocument()
})

debug

it('will print the DOM in the console', () => {
  const { debug } = render(<Component />)
  debug() // prints DOM in the console
})

Mocks

Clear mocks boilerplate

beforeEach(() => {
  jest.clearAllMocks()
})

Mock API requests

const postJsonMock = postJson as jest.Mock; // TS hack to get auto-completion
when(postJsonMock)
    .calledWith(expect.stringMatching(/.*api\/items.*/))
    .mockReturnValue(
        Promise.resolve({
            json: () => ({items: ["Hello World"]})
            })
    );
CC BY-NC 4.0 2024 © Shu Ding.