如何使用 Jasmine 模拟另一个模块中所需的模块
How to mock a module that is required in another module with Jasmine
const Client = require('./src/http/client');
module.exports.handler = () => {
const client = new Client();
const locationId = client.getLocationId(123);
};
我如何测试此模块以断言 client.getLocationId
已在 Jasmine 中使用 123
参数调用?
我知道如何用 Sinon 实现它,但我对 Jasmine 毫无头绪。
你会和诗乃一起做什么:
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);
const Client = require('./src/http/client');
module.exports.handler = () => {
const client = new Client();
const locationId = client.getLocationId(123);
};
我如何测试此模块以断言 client.getLocationId
已在 Jasmine 中使用 123
参数调用?
我知道如何用 Sinon 实现它,但我对 Jasmine 毫无头绪。
你会和诗乃一起做什么:
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);