如何在Backbone Marionette单元测试中模拟window.location.href?

时间:2018-05-21 11:31:41

标签: jasmine

  

我有一个功能,当没有找到任何存储在   cookie,重定向到指定为:

的某个页面
showEnrollRoute: function(){`*enter code here*`
            var username = Application.utils.getCookie("username");
            if(username != null || username != undefined){
                Application.vent.trigger("refresh:header");
                var channel = module.getChannel("counties");
                channel.then(function(channel){
                    channel.request("fetQuestions");
                }); 
            } else {
                console.log("Start");
                window.location.href= Application.getConfig("logoutSuccess");//error point
                console.log("End");
            }   
        }
  

window.location.href导致单元测试失败。

     

您的部分测试会进行整页重新加载。

     

我做了一些研究,发现我已经在模拟$ window对象了   单元测试以防止在运行测试时重新加载页面?

     

任何人都可以建议一个方法来解决它吗?提前谢谢!

     编辑:这个问题是一样的,但问题现在不同了。我有   发现在test-case中模拟$ window对象会   停止发生错误。任何人都可以建议一种方法   去吧?

1 个答案:

答案 0 :(得分:0)

最好的做法是将location.href替换为location对象提供的setter方法。

如果您希望用户能够返回历史记录,请使用location.assign(<URL>),或者使用location.replace(<URL>)来避免浏览器历史记录的输入。

.assign()

.replace()

现在,您可以在测试中模拟这些功能。可以使用手动覆盖,也可以使用sinonjs之类的模拟库。

测试可能如下:

it('should call correct URL', () => {
  const expected = '<URL>';

  sinon.stub(location, 'assign');

  // other setup if required

  showEnrollRoute();

  expect(location.assign).toHaveBeenCalledWith(expected);

  location.assign.restore();
});
相关问题