一、场景
当封装方法中需要请求接口时得单体测试
二、代码案例
// 先引用接口
import { postExecuteApi } from '../api';
jest.mock('../api');
jest.mock('../utils/service');
// 调用接口
const resultData = {
status: 200,
data: {
data: {
fail: ["Item_0"],
success: [],
}
},
};
beforeEach(() => {
// TS 写法( js 写法可以直接使用,去掉any)
(postExecuteApi as any).mockClear();
(postExecuteApi as any).mockImplementationOnce(
() => Promise.resolve(resultData),
);
});
// 进行测试
describe('the function postExecuteFun runs normally', () => {
it('The function refreshAssociatedDeviceList runs well with true', async () => {
const data: any = [
{
GUID: '9fa3e870-ca60-49cc-bf4c-fb47fe286943',
},
];
(postExecuteApi as any).mockClear();
(postExecuteApi as any).mockImplementationOnce(
() => Promise.resolve(resultData),
);
const result = await postExecuteFun(data);
expect(result).not.toBeNull();
});
});