How Can I Test Antd's useMessage() Hook with React Testing Library?

Testing the useMessage() hook

Hello. I need to test antd's useMessage() hook with React Testing Library. I'm new to testing and don't know how to solve my problem. You can show on the example of one of the methods, for example messageApi.info(). Please help me.

Now i have this code:

test('info message', async () => {
  const { result } = renderHook(() => useMessage(), {
    wrapper: Wrapper
  });
  const messageApi = result.current[0];
  const messageInfo = () =>
    messageApi.info({
      content: 'test'
    });
});

How can I test that a message appears with the text 'test'?

1 Answer

I have found a solution to my question. So in order to test the appearance of a message with a certain text, you need to do this:

test('info message', async () => {
  const { result } = renderHook(() => useMessage());
  const [messageApi, contextHolder] = result.current;
  render(
      <Container>
        {contextHolder}
        <button
          onClick={() =>
            messageApi.info({
              content: <div data-testid="test-id">Some message</div>
            })
          }
        >
          Info
        </button>
      </Container>
  );
  const button = await screen.findByRole('button');
  fireEvent.click(button);
  const message = await screen.findByTestId('test-id');
  expect(message).toBeInTheDocument();
  expect(message).toHaveTextContent('Some message');
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest