typescript - 如何模拟 Auth.currentSession()?
问题描述
我尝试模拟 Auth.currentSession() 进行开玩笑测试。
我尝试根据这篇文章编写代码。
https://github.com/aws-amplify/amplify-js/issues/3605
但它不起作用。它会产生编译错误。
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 })
~~~~
请给我解决方案以使此 Auth 模拟工作。
索引.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).
};
索引.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);
});
})
解决方案
我只是可以通过添加@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);
}
推荐阅读
- php - 如何在 woocommerce rest api 中获取运费?
- python - SQL Alchemy 会话从 Postgres 返回相同的数据
- c# - 使用 DynamicData 的数据虚拟化
- python - Python中的操作系统独立路径导入
- php - 如何使用 symfony 棘轮向特定的 websocket 客户端发送消息?
- ms-access - 'Microsoft.ACE.OLEDB.12.0' 提供程序未在本地计算机上注册
- reactjs - 在条纹中添加客户的信用卡信息
- tcp - UDP Socket 如何处理差异主机
- python - 如何在python中正确使用一系列独立的if语句来获得正确的输出?
- html - 访问的链接不起作用如何修复它