我目前正在编写一个 Google Chrome 扩展程序并使用 Jasmine 1.3.0 对其进行测试。该扩展是一个相当简单的字典扩展,它接受用户双击突出显示的单词,将其传递到后台,并进行一些字典调用以在弹出窗口中显示。现在我正在尝试测试后台是否确实接收使用 requireJS ( http://requirejs.org/ ) 从内容脚本传递的消息。我的第一个测试(调用 addListener
)通过了,但后续测试失败了。这是background_spec.js:
describe("background message passing", function() {
beforeEach(function() {
chrome = {
runtime : {
onMessage : {
addListener : function() {}
}
}
}
spyOn(chrome.runtime.onMessage, 'addListener').andCallThrough();
});
it("should add a listener", function() {
runs(function() {
require(['background']);
});
waits(100);
runs(function() {
expect(chrome.runtime.onMessage.addListener).toHaveBeenCalled();
});
});
it("should call the listener with a function", function() {
runs(function() {
require(['background']);
});
waits(100);
runs(function() {
expect(chrome.runtime.onMessage.addListener).toHaveBeenCalledWith(
jasmine.any(Function));
});
});
it("should save the input", function() {
runs(function() {
require(['background']);
});
waits(100);
runs(function() {
var word;
listener = chrome.runtime.onMessage.addListener.mostRecentCall.args[0];
expect(listener).toBeDefined();
/*
listener({input: "foo"}, {}, function(){});
expect(word).toBeDefined();
expect(word).toEqual("foo");
*/
});
});
});
第二个规范,我称之为 haveBeenCalledWith
,表示根本没有调用 addListener
。第三个规范报告 mostRecentCall.args
未定义,并且无法访问未定义的属性 0。 (进一步调试显示 mostRecentCall
返回一个空对象。)
这里是background.js,作为一个很好的衡量标准:
var word;
chrome.runtime.onMessage.addListener(
function(msg, sender, sendResponse) {
if (msg.input) {
word = msg.input;
sendResponse({success: "Message received"});
}
});
如果有人能看出我的错误是什么,我将不胜感激。我对 Jasmine 和 requireJS 都很陌生,我已经没有办法尝试了。
最佳答案
我正在使用 Jasmine 2.0.0,我所做的唯一一件事就是将 var
添加到 chrome 对象:
var chrome ;
beforeEach(function(){
chrome = {
runtime : {
onMessage : {
addListener : function() {}
}
}
}
spyOn(chrome.runtime.onMessage, 'addListener').andCallThrough();
});
关于javascript - Jasmine spy 返回空的mostRecentCall 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21146726/