微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

单元测试 – 如何在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();
    });
  });
});

原文地址:https://www.jb51.cc/js/157851.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐