我是在Typescript环境中学习玩笑的新用户。
是否有人使用jest spyOn
方法测试节点模块库中对函数的调用或能够成功模拟函数?我在打字稿环境中使用玩笑,并尝试在typesafe-actions库中测试功能。
下面的代码清单中提供了一个有关如何尝试使用spyOn的小示例:
import * as typ from 'typesafe-actions';
import { factoryAllPostsAction } from './actions';
describe('action test', ()=>{
test('test factoryAllPostsAction', ()=>{
const mockCreateAsync = jest.spyOn(typ, 'createAsyncAction');
// example wrapper method that calls createAsyncAction
// in this case it creates an instance of allPosts action
const asyncAction = factoryAllPostsAction();
expect(mockCreateAsync).toHaveBeenCalled();
});
});
我已经上传了小型示例项目here。 该测试位于 src / features / post / actions.spec.ts 文件中。
我还尝试过在下面的代码清单中创建手动模拟,这会返回错误bash TypeError: (0 , _typesafeActions.createAsyncAction)(...) is not a function.
jest.mock('typesafe-actions', () => {
const originalModule = jest.requireActual('typesafe-actions');
return {
__esModule: true,
...originalModule,
createAsyncAction: jest.fn().mockReturnValue({}),
};
});
import {createAsyncAction} from 'typesafe-actions';
import { factoryAllPostsAction } from './actions';
describe('action test', ()=>{
test('test factoryAllPostsAction', ()=>{
// example wrapper method that calls createAsyncAction
// in this case it creates an instance of allPosts action
const asyncAction = factoryAllPostsAction();
expect(createAsyncAction).toHaveBeenCalled();
});
});