redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

Cannot read properties of undefined (reading 'token') RTKQ

Open rue-oplo opened this issue 3 years ago • 3 comments

export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({
    baseUrl: baseURL,
    prepareHeaders: (headers, { getState }) => {
      const token = (getState() as RootState).auth.token; // this block of code is new
      if (token) {
        headers.set('authorization', `Bearer ${token}`);
      }
      return headers;
    },
  }),
  tagTypes: ['CaseSummaryResponseInterface'],
  endpoints: builder => ({
    getTableDataByName: builder.query<CaseSummaryResponseInterface, CaseSummaryRequestInterface>({
      query: body => ({
        url: 'case-summary',
        method: 'POST',
        body,
      }),
      transformResponse: (response: any) => response.data,
    }),
});

The above code is how we're currently fetching table data and we've now added the token in on request, which breaks the tests. Any suggestions on how we would go about fixing this?

rue-oplo avatar Jul 07 '22 18:07 rue-oplo

It seems that in your tests, state.auth is undefined. Are you testing with a mock store that does not have auth?

phryneas avatar Jul 07 '22 20:07 phryneas

Yeah the auth isn't handled by the store, how should I mock auth in the store?

rue-oplo avatar Jul 07 '22 20:07 rue-oplo

Use a real store, don't use a mock store. See our recommendations in https://redux.js.org/usage/writing-tests

phryneas avatar Jul 07 '22 21:07 phryneas