Search code examples
reactjsjestjsreact-testing-libraryrtk-querymsw

React-Testing Library and MSW v2 renderHook returns no data on RTKQ


I have set up a test so that I can test a RTKQ to return a simple json back. I get the IsSuccess true but data us undefined. Can see it go from isLoading to is Success so the call is being observed to some degree.

const handlers = [
    http.post(`${BASE_URL_TOKEN}`, () =>
        HttpResponse.json({})
    ),
    http.get(`${BASE_URL}/admin/test`, () => {

        return HttpResponse.json({ data: 'Hello World' });
    }),
];

const server = setupServer(...handlers);

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));

afterEach(() => {
    server.resetHandlers();
});

afterAll(() => {
    server.close();
});

const wrapper = ({ children }) => <Provider store={store}> 
         {children}</Provider>;


test('renders hook', async () => {
    const { result } = renderHook(() => useTestQuery(), {
        wrapper,
    });


    await waitFor(() => expect(result.current.isSuccess).toBe(true));

    console.log('expect to see data', result.current);

    expect(result.current.data).toBeDefined();
});

api layer

export const adminApi = createApi({
    reducerPath: 'admin-Api',
    baseQuery: fetchBaseQuery({ baseUrl: `${BASE_URL}/admin/` }),
    endpoints: (builder) => ({
        test: builder.query<Test, void>({
            query: () => ({
                url: 'test',
                method: httpMethod.Get,
            }),
        }),
    }),
});

model

export interface Test {
    data: string;
}

Tried several approaches using RTKQ and React Testing Library but cannot get data to pass. Not sure if its an issue with MSW or React Testing Library. Any advice welcome.


Solution

  • This route ended up never working. I ended up downgrading MSW to version 1.3 and avoiding version two's approach altogether for accessing API endpoints. This solved the issue for us.