Jasmine mock window.location.reload(true);

Jasmine mock window.location.reload(true);,jasmine,mocking,karma-jasmine,reload,window.location,Jasmine,Mocking,Karma Jasmine,Reload,Window.location,我有一个js对象的构造函数,如下所示: function SomeThing(window, document) { var self = this; self.window = window; self.document = document; if (!self.window.sessionStorage.getItem('page-reloaded')) { self.window.sessionStorage.setItem('page-reload

我有一个js对象的构造函数,如下所示:

function SomeThing(window, document) {
   var self = this;
   self.window = window;
   self.document = document;

   if (!self.window.sessionStorage.getItem('page-reloaded')) {
      self.window.sessionStorage.setItem('page-reloaded', true);
      self.window.location.reload(true); // PROBLEM ON THIS LINE
      return;
   }
}
beforeEach(function() {
  mockWindowObj = {
    'location': {
        'href': '',
        'search': '?hello=world',
        'pathname': '/some/path',
        'replace': function () {},
        'reload': jasmine.createSpy()
      }
   };

  spyOn(mockWindowObj.location, 'reload').and.callFake(function(){}); ;

  some = new SomeThing(mockWindowObj, mockDocumentObj);
});
我的模拟测试如下所示:

function SomeThing(window, document) {
   var self = this;
   self.window = window;
   self.document = document;

   if (!self.window.sessionStorage.getItem('page-reloaded')) {
      self.window.sessionStorage.setItem('page-reloaded', true);
      self.window.location.reload(true); // PROBLEM ON THIS LINE
      return;
   }
}
beforeEach(function() {
  mockWindowObj = {
    'location': {
        'href': '',
        'search': '?hello=world',
        'pathname': '/some/path',
        'replace': function () {},
        'reload': jasmine.createSpy()
      }
   };

  spyOn(mockWindowObj.location, 'reload').and.callFake(function(){}); ;

  some = new SomeThing(mockWindowObj, mockDocumentObj);
});
当我运行测试时,会出现以下错误:

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
 {
   "message": "Some of your tests did a full page reload!",
   "str": "Some of your tests did a full page reload!"
 }

如果我在
window.location.reload(true)
行外注释,我的所有测试运行正常并通过。我对单元测试有点陌生,我不知道该如何解决这个问题。任何帮助都将不胜感激。提前感谢。

您发布的代码不能是您实际运行的代码。包含self.window.sessionStorage.getItem的行必须失败,因为您没有在模拟上定义sessionStorage


我猜调用SomeThing函数时,window指向真实的window对象。这就解释了你所观察到的情况。

谢谢你的回答,我刚刚弄明白了。我是个白痴,在文件的底部启动了这个对象。所以它运行测试时没有看到我的模拟对象在其轨道上停止测试。。。呃(对我发牢骚)。我是在嘲笑sessionStorage,我只是没有把它贴在问题上以保持简单。