【问题标题】:Testing a vue-componet which uses a filter测试使用过滤器的 vue 组件
【发布时间】:2019-03-11 03:24:15
【问题描述】:

我有以下组件:

<template>
    <div class="lead-segment">
        <div v-html="insuranceType()"></div>
    </div>
</template>
<script>
 import Vue from 'vue';

 export default {
   name: 'lead-segment',
   props: {
     rowData: {
       type: Object,
       required: true,
     },
     rowIndex: {
       type: [Number, String],
     },
   },
   methods: {
     insuranceType() {
       const contribution = Vue.filter('currencyFilter')(this.rowData.additionalCustomerInfo.contribution);
       return `${this.rowData.leads.insurance_type.name}<br/>${contribution}`;
      },
    },
  };
</script>

还有下面的测试,用 karma/jasmine 和 vue-test-utils 编写。

import { createLocalVue, shallowMount } from '@vue/test-utils';
import LeadSegmentComponent from './LeadSegmentComponent';
import { currencyFilter } from '../filters';

describe('LeadSegmentComponent', () => {
  const localVue = createLocalVue();
  localVue.filter('currencyFilter', currencyFilter);

  const wrapper = shallowMount(LeadSegmentComponent, {
    localVue,
    propsData: {
      rowData: {
        additionalCustomerInfo: {
          contribution: 1,
        },
        leads: {
          insurance_type: {
            name: '',
          },
        },
      },
    },
  });
  const vm = wrapper.vm;

  it('should be build', () => {
    expect(vm)
      .toBeDefined();
  });
});

如果我执行测试,我会收到以下错误:

"message": "afterAll 中抛出一个错误\nTypeError: __WEBPACK_IMPORTED_MODULE_0_vue___default.a.filter(...) is not a function\n

如果我删除组件中使用的过滤器,则测试通过。

为什么我在测试中添加了 Vue.filter 却不是一个函数?正确的做法是什么?

提前致谢

【问题讨论】:

    标签: vue.js vue-test-utils


    【解决方案1】:

    我也有类似的问题。

    到目前为止,我通过在我的测试代码中导入 Vue 并全局注册过滤器来解决。我不喜欢它,我宁愿不污染全局范围,但在“localVue”上声明它似乎不起作用:

    import Vue from 'vue';
    import myFilter from './myFilter';
    
    describe('MyComponent', () => {
        Vue.filter('myFilter', myFilter);
        // test code...
    });
    

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 2018-08-24
      • 2021-10-02
      • 2019-04-19
      • 2023-01-03
      • 2018-07-25
      • 2019-07-16
      • 1970-01-01
      • 2013-01-05
      相关资源
      最近更新 更多