const Client = require('./src/http/client');
module.exports.handler = () => {
const client = new Client();
const locationId = client.getLocationId(123);
};
如何测试此模块断言已使用Jasmine中的client.getLocationId
参数调用123
?
我知道如何用Sinon实现这一点,但我对Jasmine没有任何线索。
答案 0 :(得分:2)
Sinon你会做什么:
Sinon.spy(client, 'getLocationId');
...
Sinon.assert.calledWith(client.getLocationId, 123);
与Jasmine一起做:
spyOn(client, 'getLocationId');
...
expect(client.getLocationId).toHaveBeenCalledWith(123);
更新:因此,您需要的是在您正在测试的模块需要时模拟Client
模块。我建议使用Proxyquire:
const proxyquire = require('proxyquire');
const mockedClientInstance = {
getLocationId: () => {}
};
const mockedClientConstructor = function() {
return mockedClientInstance;
};
const moduleToTest = proxyquire('moduleToTest.js', {
'./src/http/client': mockedClientConstructor
});
这会将您的模拟作为依赖项注入,这样当您测试的模块需要./src/http/client
时,它将获得您的模拟而不是真正的Client
模块。在此之后,您只是正常监视mockedClientInstance
中的方法:
spyOn(mockedClientInstance, 'getLocationId');
moduleToTest.handler();
expect(mockedClientInstance.getLocationId).toHaveBeenCalledWith(123);