如何在VueJS中测试计算属性?

时间:2017-04-03 15:38:26

标签: unit-testing jasmine vue.js

我正在使用Vue CLI中的VueJS。所以我的所有组件都是.vue格式。

在我的一个组件中,我在数据部分有一个名为fields的数组。

//Component.vue
data() {
  return {
     fields : [{"name" : "foo", "title" : "Foosteria"}, {"name" : "bar", "title" : "Barrista"}]
  }
}

我有计算属性,它是fields

的子集
//Component.vue
computed : {
    subsetOfFields () {
       // Something else in component data determines this list
    }
}

我已经在jasmine这样设置了所有单元测试,并且工作正常。

 //Component.spec.js
 import Vue from 'vue'
 import MyComponent from 'Component.vue'
 describe("Component test", function() {
      var myComponentVar = new Vue(MyComponent);
      var vm = myComponentVar.$mount();

      beforeEach(function() {
         vm = myComponentVar.$mount();
      );

      afterEach(function() {
         vm = myComponentVar.$destroy();
      });

      it("First spec tests something", function() {
            ...
       });

 });

对于其他所有内容,在spec内部执行某些操作,然后在data对象上运行断言就可以了。但是,在subsetOfFields上运行断言始终返回一个空数组。为什么这样?我该怎么办才能测试呢?

仅供参考,我甚至尝试将规范嵌套在另一个describe块中,然后添加beforeEach来初始化fields数组。它不起作用。

但是,在通用fields函数内初始化beforeEach有效。但我不想用其他规格的模拟数据初始化fields数组。

1 个答案:

答案 0 :(得分:3)

我遇到了这个关于测试的链接,你需要看的部分是Vue.nextTick(...)部分

https://alligator.io/vuejs/unit-testing-karma-mocha/

我正在讨论的块如下:

import Vue from 'vue';
// The path is relative to the project root.
import TestMe2 from 'src/components/TestMe2';

describe('TestMe2.vue', () => {
  ...
  it(`should update when dataText is changed.`, done => {
    const Constructor = Vue.extend(TestMe2);

    const comp = new Constructor().$mount();

    comp.dataProp = 'New Text';

    Vue.nextTick(() => {
      expect(comp.$el.textContent)
        .to.equal('New Text');
      // Since we're doing this asynchronously, we need to call done() to tell Mocha that we've finished the test.
      done();
    });
  });
});
相关问题