我有一个名为 map-creation.service.ts
的模块:
export const createMap = (asyncJobId: string, resourceUrl: string, s3DestFolder: string) => {
};
在我的端点中使用:
import {createMap} from './services/map-creation.service';
const router = express.Router();
const routePrefix = config.get('server.routePrefix');
router.post(`/${routePrefix}`, validate(validation), (req: express.Request, res: express.Response) => {
createMap(req.body.asyncJobId, req.body.resourceUrl, req.body.s3DestFolder);
res.status(201).json({message: 'Created'});
});
当我试图在我的测试中模拟这个模块,并想测试它是否在请求端点时被调用,我仍然得到:Expected mock function to have been called with: ... 但它是未调用。
jest.mock('../../../src/services/map-creation.service');
import {createMap} from '../../../src/services/map-creation.service';
这是我的测试:
it('should call the map-creation service', () => {
return request(server)
.post(`/${routePrefix}`)
.send({
asyncJobId,
resourceUrl,
s3DestFolder
})
.then(res => {
expect(createMap).toBeCalledWith(asyncJobId, resourceUrl, s3DestFolder);
});
});
如果我像这样模拟这个方法:
import {createMap} from '../../../src/services/map-creation.service';
createMap = jest.fn();
测试通过,但 tslint 提示:无法分配给“createMap”,因为它不是变量
。那么在 TypeScript 和 Jest 中模拟此方法的正确方法是什么?
最佳答案
So what would be the proper way to mock this method in TypeScript and Jest?
使用依赖注入(inject)根据需要注入(inject)函数的模拟版本和真实版本。
推荐的 DI 框架:http://inversify.io/
but tslint is complaining: Cannot assign to 'createMap' because it is not a variable
请不要这样做。导入应该被认为是不可变的。您也会为此收到编译时 TypeScript 错误,当模块支持成为 native 时,您将收到运行时错误。
关于typescript - 如何使用 Jest 在 TypeScript 中模拟导入的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43473218/