【问题标题】:How to test vue component method with ajax request in Mocha?如何在 Mocha 中使用 ajax 请求测试 vue 组件方法?
【发布时间】:2018-02-27 23:07:40
【问题描述】:

我有一个带有方法的vue组件发送ajax请求,我尝试了Mocha提供的done()来测试这个方法,但是覆盖率报告似乎不能正常工作(成功和完整的方法没有根据那个报告)。代码如下:

  • demo.vue 中的 Vue 组件代码

```

loadData: function(cb) {
      var that = this;
      $.ajax(
        {
          url: "/api/nodesWithTask",
          async: true,
          success: function(data) {
            that.nodes = data;
          },
          complete: function(xhr, status) {
            if (cb && typeof (cb) == 'function') {
              cb.call();
            }
          }
        }
      );
    }

```

  • 测试代码

```

import Vue from 'vue'
import demo from '@/components/demo'
describe('demo.vue', () => {
  var mockData = {"id":"abc"};
  var server;
  var vm;
  before(function () { 
    server = sinon.fakeServer.create(); 
    //mock response for ajax request
    server.respondWith("/api/nodesWithTask",[200,{"Content-Type":"application/json"},JSON.stringify(mockData)]);
    const Constructor = Vue.extend(demo);
    vm = new Constructor().$mount();
  });

  after(function () { server.restore(); });

  it('load data async', (done) => {
    vm.loadData(function(){
      done();
    });
  })
})

```

提前感谢您的任何建议。

【问题讨论】:

    标签: vue.js mocha.js


    【解决方案1】:

    在领导的建议下,我找到了一个sinon fake server的magic配置选项如下

    before(function () { 
        server = sinon.fakeServer.create(); 
        //mock response for ajax request
        server.respondWith("/api/nodesWithTask",[200,{"Content-Type":"application/json"},JSON.stringify(mockData)]);
        server.respondImmediately = true;
        const Constructor = Vue.extend(demo);
        vm = new Constructor().$mount();
      });
    

    在我将 respondImmediately 选项设置为 true 后,测试就可以正常运行了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 2020-03-05
      • 2019-06-24
      • 2016-10-19
      • 2020-03-06
      相关资源
      最近更新 更多