【问题标题】:Vue unit tests - cannot read property 't' of undefinedVue单元测试-无法读取未定义的属性't'
【发布时间】:2019-12-30 23:01:57
【问题描述】:

我正在使用 jest 运行 vue 单元测试来检查各个组件的输出。该组件使用 vuetify。

我创建了一个vue实例来挂载组件:

import myComponent from './MyComponent.vue';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';

describe('Component', () => {
    let wrapper;

    const router = new VueRouter({
        base: '/ui/',
        routes: [
            {
                name: 'myRoute',
                path: '/route-to-my-component',
                component: myComponent
            },
        ]
    });

    beforeEach(() => {
        const localVue = createLocalVue();
        localVue.use(VueRouter);
        localVue.use(Vuetify);

        wrapper = mount(myComponent, {
            localVue: localVue,
            router
        });
    });



    it('contains a container', () => {
      expect(wrapper.contains('v-container')).toBe(true);
    })
});

我希望这个测试能够通过,但我得到的是TypeError: Cannot read property 't' of undefined

作为参考,我关注了https://fernandobasso.github.io/javascript/unit-testing-vue-vuetify-with-jest-and-vue-test-utils.html

【问题讨论】:

  • 从测试工具导入的createLocalVue 在哪里?
  • 我还不能发表评论。请编辑您的问题并提供组件的代码。由于该错误与t 有关,这很可能是翻译问题。您需要在测试中模拟翻译模块。

标签: vue.js vuetify.js vue-test-utils


【解决方案1】:

为了在 vuetify 之上运行 vue 单元测试,需要一些(有些随机的)东西:

  1. 根据this 评论,避免使用 createLocalVue()。

  2. 某些组件(如自动完成)需要 $vuetify.lang$vuetify.theme 进行模拟

您的规范应如下所示:

import Vuetify from 'vuetify';
import Vue from 'vue';

Vue.use(Vuetify);

it('contains a container', () => {
  const wrapper = mount(FreeAutocomplete, {
    created() {
      this.$vuetify.lang = {
        t: () => {},
      };
      this.$vuetify.theme = { dark: false };
    }
  });

  expect(wrapper.contains('v-container')).toBe(true);
})

【讨论】:

  • 执行此操作时找不到“this”范围。
猜你喜欢
  • 1970-01-01
  • 2017-06-16
  • 2021-12-02
  • 2017-10-13
  • 1970-01-01
  • 2020-12-12
  • 2020-01-17
  • 2019-09-16
  • 2017-04-04
相关资源
最近更新 更多