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

Div*_*raj 8 unit-testing jasmine vue.js

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

在我的一个组件中,我fields在数据部分中调用了一个数组.

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

我有一个计算属性是一个子集fields

//Component.vue
computed : {
    subsetOfFields () {
       // Something else in component data determines this list
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经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() {
            ...
       });

 });
Run Code Online (Sandbox Code Playgroud)

对于其他一切,在内部做一些事情spec,然后在data对象上运行断言就可以了.但是,运行断言subsetOfFields始终返回一个空数组.为什么这样?我该怎么办才能测试呢?

仅供参考,我甚至尝试将规范嵌套在另一个describe块中,然后添加一个beforeEach初始化fields数组.那没起效.

但是,fields在泛型beforeEach函数内部进行初始化是有效的.但我不想fields用其他规格的模拟数据初始化数组.

Joe*_*Foo 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();
    });
  });
});
Run Code Online (Sandbox Code Playgroud)