Mar*_*rök 5 unit-testing mocking typescript jestjs
我有一个名为的模块map-creation.service.ts
:
export const createMap = (asyncJobId: string, resourceUrl: string, s3DestFolder: string) => {
};
Run Code Online (Sandbox Code Playgroud)
在我的端点中使用了哪个:
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'});
});
Run Code Online (Sandbox Code Playgroud)
当我尝试在测试中模拟该模块,并想测试在请求端点时是否调用了该模块时,我仍然得到: 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';
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
it('should call the map-creation service', () => {
return request(server)
.post(`/${routePrefix}`)
.send({
asyncJobId,
resourceUrl,
s3DestFolder
})
.then(res => {
expect(createMap).toBeCalledWith(asyncJobId, resourceUrl, s3DestFolder);
});
});
Run Code Online (Sandbox Code Playgroud)
如果我嘲笑这样的方法:
import {createMap} from '../../../src/services/map-creation.service';
createMap = jest.fn();
Run Code Online (Sandbox Code Playgroud)
测试通过,但是tslint抱怨:Cannot assign to 'createMap' because it is not a variable
。那么在TypeScript和Jest中模拟此方法的正确方法是什么?
那么在 TypeScript 和 Jest 中模拟此方法的正确方法是什么?
使用依赖项注入根据需要注入模拟版本和真实版本的函数。
DI 推荐框架: http: //inversify.io/
但 tslint 抱怨:无法分配给“createMap”,因为它不是变量
请不要这样做。导入应该被认为是不可变的。您也会因此收到编译时 TypeScript 错误,当模块支持成为本机时,您将收到运行时错误。
归档时间: |
|
查看次数: |
3372 次 |
最近记录: |