使用mocha / chai在AJAX请求中对window.location.href进行单元测试

时间:2017-01-06 23:49:44

标签: jquery unit-testing mocha chai teaspoon

我需要测试window.location.href = data.redirect_path是否曾经发生过。我怎么会在Sinon中嘲笑它而不将它从我的测试运动员身上移开?我正在使用带茶匙的chai / mocha.js作为我的测试跑步者。

$.ajax({
    type: 'PUT',
    url: $url,
    dataType: 'json',
    data: { user: $userData },
    success: function(data) {
      if (data.success == true) {
        window.location.href = data.redirect_path
      } else {
        $errorsContainer.html(data.html);
        $codeInput.select();
        if (typeof data.redirect_path !== 'undefined') {
          window.location.href = data.redirect_path
        }              
      }
    }
  });

2 个答案:

答案 0 :(得分:1)

在过去的2-3个小时里,我因为类似的问题而拔头发。不幸的是,使用window.location = href导航是我插件中非常重要的一个行为,因此我不能仅仅依靠信仰。以上使用window.location.assign(href)对我不起作用 - 可能是由于jsdom,不确定。

最后,我提出了一个(相当)简单的解决方案,适用于我的情况。

it('reloads the page when using the browsers back button', (done) => {
    let stub = sinon.stub(window, 'location').set(() => { done() });

    // do whatever you need to here to trigger
    // window.location = href in your application
});

我知道它在长时间超时运行,所以当它失败时你必须等待它,但这比我没有测试证明我的插件表现得如预期更好。

  

注意jsdom 最初为window.location设置了设置器,但sinon允许您创建一个设置器。

答案 1 :(得分:0)

您可以stub $ ajax success: function(data) { if (data.success == true) { window.location.assign(data.redirect_path) } else { $errorsContainer.html(data.html); $codeInput.select(); if (typeof data.redirect_path !== 'undefined') { window.location.assign(data.redirect_path); } } } ,如下所示。这需要对您的代码进行一些重构,以便它易于测试。

你的成功回调需要像这样,

location.assign

请参阅doc it("should fake successful ajax request", function () { sinon.stub($, "ajax").yieldsTo("success", {redirect_path: '/home', success: true}); sinon.stub(window.location, 'assign'); // stubbing the assign. so that it wont redirect to the given url. //here you call the function which invokes $.ajax(); someFunction(); // assert here // manually restoring the stubs. $.ajax.restore(); window.location.assign.restore(); }) 工作原理。

public class Details {
    private Link link;
    private List<Comment> comments;
}

Observable<Details> detailsObservable = ...;
相关问题