redux-toolkit
redux-toolkit copied to clipboard
Cannot read properties of undefined (reading 'token') RTKQ
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?
It seems that in your tests, state.auth is undefined. Are you testing with a mock store that does not have auth?
Yeah the auth isn't handled by the store, how should I mock auth in the store?
Use a real store, don't use a mock store. See our recommendations in https://redux.js.org/usage/writing-tests