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.
https://ant.design/components/message
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'?
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');
});