I try to mock Auth.currentSession() for jest testing.
I tried to write code according to this article.
https://github.com/aws-amplify/amplify-js/issues/3605
But it does not work. It makes compile errors.
services/ui/wait-step-check/index.spec.ts:10:3 - error TS2345: Argument of type '{ getAccessToken: () => { getJwtToken: () => string; }; }' is not assignable to parameter of type 'Promise<CognitoUserSession>'.
Object literal may only specify known properties, and 'getAccessToken' does not exist in type 'Promise<CognitoUserSession>'.
10 getAccessToken: () => ({
~~~~~~~~~~~~~~~~~~~~~~~~
11 getJwtToken: () => ("Secret-Token")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
12 })
~~~~
Please give me the solution to make this Auth mock work.
index.ts
export const waitDoneCheckProcessing = async (
operationId: number,
watchStatusSelector: WatchSelector,
timeoutId?: any,
options?: { intervalSec?: number },
): Promise<EnumCheckStatus | null> => {
// (omitted).
const auth = await Authorization();
const res = await client.getV1OperationsIdProgress(operationId, auth);
// (omitted).
};
index.spec.ts
import {waitDoneCheckProcessing} from "~/services/ui/wait-step-check/index";
import axios from "axios";
import {EnumCheckStatus} from "~/services/openapi";
import Auth from '@aws-amplify/auth'
jest.mock('axios');
const mockAxios = axios as jest.Mocked<typeof axios>;
// I want to make this mock work.
jest.spyOn(Auth, 'currentSession').mockReturnValue({
getAccessToken: () => ({
getJwtToken: () => ("Secret-Token")
})
});
describe('wait-step-check', () => {
beforeEach(() => {
mockAxios.request.mockClear();
let counter = 0;
mockAxios.request.mockImplementation(() => {
counter ;
return Promise.resolve<any>({
data: {
impairment1: {
checkStatus: counter >= 3 ? EnumCheckStatus.Done : EnumCheckStatus.Processing,
},
},
})
})
});
it('check', async () => {
await waitDoneCheckProcessing(
1,
(res) => res.impairment1.checkStatus,
{
intervalSec: 100,
});
expect(mockAxios.request).toBeCalledTimes(3);
});
})
CodePudding user response:
I just can avoid compile error by adding @ts-ignore
it('check', async () => {
// @ts-ignore
jest.spyOn(Auth, 'currentSession').mockImplementation(() => ({
getIdToken: () => ({
getJwtToken: () => 'mock',
}),
}));
await waitDoneCheckProcessing(
1,
(res) => res.impairment1.checkStatus,
{
intervalSec: 100,
});
expect(mockAxios.request).toBeCalledTimes(3);
}