I have the following hook:
function useWelcomeMessage() {
const { data, error} = useGetWelcomeMessage();
const printMessage = useCallback(async () => {
if (data) {
alert(data)
}
if (error) {
throw new Error(error);
}
}, [data, error]);
return { printMessage };
}
export default useWelcomeMessage;
I'm trying to write a test for it using vitest to make sure that alert(data).
const mockMessage = 'hello world';
const server = setupServer(
http.get('*/api/v1/getMessage', () => {
return HttpResponse.text(mockMessage);
})
);
it('calls alert with the data', async () => {
const { result } = renderHook(() => useWelcomeMessage(), {
wrapper: ({ children }) => <Provider store={store}>{children}</Provider>,
});
await act(async () => {
await result.current.printMessage();
});
expect(alert).toHaveBeenCalledWith(mockMessage);
});
My problem is, that when I invoke printMessage, the useGetWelcomeMessage hasn't had time to execute yet, and thus data is still undefined.
I'm trying to figure out the best way to wait for the RTK Query call to have completed. I tried fake timers and advancing those to no effect. A solution that did work, was having a vi.fn() in the MSW get handler, and waiting on that to have been called before proceeding with the test.