Vue.js - 测试异步返回的数据

时间:2016-11-09 09:50:50

标签: unit-testing mocha vue.js vue-resource

我有以下示例:

<!DOCTYPE html>
<html>
  <head>
    <title>Mocha</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="mocha.css" />
  </head>
  <body>
    <div id="mocha"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.1.2/mocha.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>

    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.0.3/vue-resource.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.15.4/sinon.js"></script>

    <script>mocha.setup('bdd');</script>
    <script>
     "use strict";
     var assert = chai.assert;
     var should = chai.should();

     var vm = new Vue({
     data: {
         message: "Hello"
     },

     methods: {
         loadMessage: function() {
         this.$http.get("/get").then(
             function(value) {
             this.message = value.body.message;
             });
         },
     }
     });
     describe('getMessage', function() {
     let server;
     beforeEach(function () {
         server = sinon.fakeServer.create();
     });

     it("should get the message", function(done) {
         server.respondWith([200, { 'Content-Type': 'application/json' },
                 JSON.stringify({message: "Test"})]);

         vm.message.should.equal("Hello");
         vm.loadMessage();
         server.respond();
         setTimeout(function() {
         // This one works, but it's quirky and a possible error is not well represented in the HTML output.
         vm.message.should.equal("Test");
         done();
         }, 100);

         // This one doesn't work
         //vm.message.should.equal("Test");
     });
     });
    </script>
    <script>
      mocha.run();
    </script>
  </body>
</html>

我想测试Vue异步从服务器获取数据。虽然,我用Sinon FakeServer模拟了实际的http请求。

当然,在调用loadMessage之后,该消息尚未设置。我可以使用超时功能进行测试,但我相信应该有更好的方法。我调查了respondImmediately,但没有改变。此外,还有可能调用done()函数。但是,据我所知,这需要在loadMessage函数内调用,因此修改了测试中的代码。

处理此问题的正确方法是什么?

编辑:我找到了至少一个部分解决方案,但似乎仍然很混乱:在mocha单元测试中调用done()函数。当断言失败时,它至少会在html输出中显示。但是,断言消息并不像正常测试那样清晰。此外,这项技术对我来说似乎仍然很混乱。

1 个答案:

答案 0 :(得分:1)

由于vue组件的更新是异步完成的,因此需要使用

// Inspect the generated HTML after a state update
  it('updates the rendered message when vm.message updates', done => {
    const vm = new Vue(MyComponent).$mount()
    vm.message = 'foo'
    // wait a "tick" after state change before asserting DOM updates
    Vue.nextTick(() => {
      expect(vm.$el.textContent).toBe('foo')
      done()
    })
  })

取自official docs