【问题标题】:Unit test for window.location.href within an AJAX request using mocha/chai使用 mocha/chai 在 AJAX 请求中对 window.location.href 进行单元测试
【发布时间】:2017-01-06 23:49:44
【问题描述】:

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

【问题讨论】:

    标签: jquery unit-testing mocha.js chai teaspoon


    【解决方案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 允许您创建一个。

    【讨论】:

      【解决方案2】:

      您可以在$ 上为ajax 提供stub,如下所示。这需要对您的代码进行一些重构,以便于测试。

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

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

      请参阅doc 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();
      })
      

      【讨论】:

        猜你喜欢
        • 2018-01-02
        • 2021-09-14
        • 1970-01-01
        • 2019-02-14
        • 1970-01-01
        • 2018-12-30
        • 1970-01-01
        • 2014-11-25
        • 2016-05-26
        相关资源
        最近更新 更多