我目前正在尝试为我的 RTKQuery 编写玩笑测试,但我被困在测试的身份验证级别上。
基本上,我使用的 api 旨在将令牌放在查询参数上,而不是放在请求标头上:"https://api/v1/something/meta/?token=userToken"
因此,当我尝试测试 api 调用时,它显示请求已被拒绝。有谁知道如何用这种情况编写测试?
这是我的 RTKQuery 端点:
// index.ts
export const rootApi = createApi({
reducerPath: "root",
baseQuery: fetchBaseQuery({baseUrl: API_ROOT}),
endpoints: () => ({});
})
// dataEndpoint.ts
const token = getToken(); // Gets the user's token from localStorage after user login
export cosnt apiWithData = rootApi.injectEndpoints({
endpoints: (build) => ({
fetchDataMetaList: build.mutation<DataType, any>({
query: ({offset = 0, size = 20, body}) => ({
// token is passed in for query param
url: `${API_URL}?offset=${offset}&size=${size}&token=${token}`,
method: "POST",
body: body || {}
})
})
})
})
以下是我的测试:
// data.test.tsx
const body = { offset: 0, size: 20, body: {} };
const updateTimeout = 10000;
beforeEach((): void => {
fetchMock.resetMocks();
})
const wrapper: React.FC = ({ children }) => {
const storeRef = setupApiStore(rootApi);
return <Provider store={storeRef.store}>{children}</Provider>
}
describe("useFetchDataMetaListMutation", () => {
it("Success", async () => {
fetchMock.mockResponse(JSON.string(response));
cosnt { result, waitForNextupdate } = renderHook(
() => useFetchDataMetaListMutation(),
{ wrapper }
)
const [fetchDataMetaList, initialResponse] = result.current;
expect(initialResponse.data).toBeUndefined();
expect(initialResponse.isLoading).toBe(false);
act(() => {
void fetchDataMetaList(body);
})
const loadingResponse = result.current[1];
expect(loadingResponse.data).toBeUndefined();
expect(loadingResponse.isLoading).toBe(true);
// Up til this point everything is passing fine
await waitForNextUpdate({ timeout: updateTimeout });
const loadedResponse = result.current[1];
// expect loadedResponse.data to be defined, but returned undefined
// console out put for loaded Response status is 'rejected' with 401 access level
// error code
})
})