gpt4 book ai didi

javascript - 如何使用 Jasmine 模拟另一个模块中所需的模块

转载 作者:行者123 更新时间:2023-12-04 01:52:09 25 4
gpt4 key购买 nike

const Client = require('./src/http/client');

module.exports.handler = () => {
const client = new Client();
const locationId = client.getLocationId(123);
};

我如何测试这个模块断言 client.getLocationId已使用 123 调用 Jasmine 的争论?

我知道如何使用诗乃来实现这一点,但我对 Jasmine 一无所知。

最佳答案

与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
});

这会将您的模拟作为依赖项注入(inject),以便当您正在测试的模块需要 ./src/http/client , 它会得到你的模拟而不是真正的 Client模块。在此之后,您只需监视 mockedClientInstance 中的方法。像平常一样:
spyOn(mockedClientInstance, 'getLocationId');
moduleToTest.handler();
expect(mockedClientInstance.getLocationId).toHaveBeenCalledWith(123);

关于javascript - 如何使用 Jasmine 模拟另一个模块中所需的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44971485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com