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

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

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

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

我有一个计算属性,它是字段的子集

//Component.vue
computed : {
    subsetofFields () {
       // Something else in component data determines this list
    }
}

我已经在这样的茉莉花中设置了所有单元测试,它们工作正常.

//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() {
            ...
       });

 });

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

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

但是,初始化通用beforeEach函数中的字段有效.但我不想用其他规范的模拟数据初始化fields数组.

解决方法

我遇到了这个关于测试的链接,你需要看的部分是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();
    });
  });
});

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...