javascript - Jasmine spy 返回空的mostRecentCall 对象

标签 javascript google-chrome google-chrome-extension requirejs jasmine

我目前正在编写一个 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/

相关文章:

javascript - 如何在新标签页上的 Chrome 扩展程序中从多功能框中窃取焦点?

javascript - requestFileSystem 在 Windows XP 上抛出 SECURITY_ERR - Chrome

javascript - Angular 5 Rxjs subject.subscribe() 不在多个组件中触发

javascript - 如何禁用 should.js 覆盖 "should"属性?

javascript - 播放音频时显示图形

javascript - 为什么我的 JS 代码在运行,而 DOM 操作还没有完成

javascript - jQuery 包含在 Chrome 上不起作用

javascript - EcmaScript 5 Google TechTalk - 范围事故 1 示例

google-chrome - pywinauto:访问 chrome gui

javascript - 无法立即在弹出窗口内立即创建 'press' 刚刚创建的按钮。我必须关闭弹出窗口,然后再次打开它(chrome-extension 弹出窗口)