如何使用Jest在TypeScript中模拟导入的函数?

马库斯·特克

我有一个名为的模块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: ... But it was not called.

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抱怨:Cannot assign to 'createMap' because it is not a variable那么在TypeScript和Jest中模拟此方法的正确方法是什么?

巴沙尔

那么在TypeScript和Jest中模拟此方法的正确方法是什么?

根据需要使用依赖注入来注入函数的模拟版本与实际版本。

推荐的DI框架:http : //inversify.io/

但tslint抱怨:因为它不是变量,所以无法分配给'createMap'

请不要这样做。进口应视为一成不变的。您还将为此而获得编译时TypeScript错误,并且当模块支持成为本地支持时,您将获得运行时错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章