我想使用 jest 框架模拟 chrome api。 例如,我使用
chrome.browserAction.setIcon
向后台脚本发送消息。如何模拟 chrome.browserAction.setIcon
或任何其他 api(例如 chrome.runtime.sendMessage
)来测试该方法是否已被调用?
我尝试使用 jest.spyOn() 来测试该方法是否已被调用。
这是测试方法
test("mock testing chrome",()=>{
spyOn(chrome,
chrome.browserAction.setIcon);
content.chromemocktest();
expect(spy).toHaveBeenCalledWith({path:"/images.png"});
});
我正在测试的方法是:
chromemocktest: function(){
chrome.browserAction.setIcon({path:"/image.png"});
}
当我运行
npm run test
来运行测试用例时,它会抛出如下所示的错误。
<spyOn> : stub() method does not exist
Usage: spyOn(<object>, <methodName>)
看一下模块@bumble/jest-chrome。我刚刚在我的 TS 项目中使用了它,效果非常好,而且超级容易使用。
问题是nodejs全局对象中不存在chrome对象。
所以你必须先创建一个模拟对象:
global.chrome = {
browserAction: {
setIcon: function () {}
}
};
之后你应该能够监视对象的方法:
spyOn(chrome, chrome.browserAction.setIcon);
如果您不想自己为 Chrome API 的每个对象创建模拟,您可以使用以下现成的解决方案。
@HarshaVardhanReddy