0

我需要测试是否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
        }              
      }
    }
  });
4

2 回答 2

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
});

我知道它在长时间超时时运行,所以当它失败时你必须等待它,但这对我来说是一个更好的权衡,而不是没有测试证明我的插件按预期运行。

NOTE最初没有设置器,但jsdom允许您创建一个。window.locationsinon

于 2018-02-03T23:16:41.653 回答
0

你可以stub$forajax如下图。这需要对您的代码进行一些重构,以便它易于测试。

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

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工作。

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();
})
于 2017-01-09T07:32:10.667 回答