【问题标题】:Error in render: "TypeError: Cannot read property '_t' of undefined" in Unit Test with Jest渲染中的错误:“TypeError:无法读取未定义的属性'_t'”在使用 Jest 的单元测试中
【发布时间】:2021-06-19 04:11:38
【问题描述】:

我为我的 Vue.js 组件编写了一个单元测试,但经过数小时的尝试和搜索互联网后,我仍然不断收到此错误:

console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884
TypeError:无法读取未定义的属性“_t”
在 Proxy.Vue.$t ([...]\node_modules\vue-i18n\dist\vue-i18n.common.js:194:17)
在 Proxy.render ([...]\src\components\Foo.vue:186:175)
在 [...]

在我的Foo.vue 组件中,我像这样使用$t,它由vue-i18n 插件提供:

<template>
  <b-form-group :label="$t('foo.label')">
    [...]
  </b-form-group>
</template>

我的Foo.spec.ts 看起来像这样:

import { createLocalVue, shallowMount, mount } from "@vue/test-utils";
import Foo from "@/components/Foo.vue";
import { i18n } from "@/i18n";

describe("Foo", () => {
  const localVue = createLocalVue() as any;
  localVue.use(i18n);
  
  const wrapper = mount(Foo, { localVue } ) as any;

  describe("removeLabel", () => {  
    it("should remove label", async () => {
      // Arrange
      const index = 1;

      // Act
      wrapper.vm.removeLabel(index);

      // Assert
      expect(wrapper.isVueInstance()).toBeTruthy();
      // [more expectations... ]
    });
  });
});

我使用相同的错误消息检查了所有其他堆栈溢出问题,但单元测试没有导致此错误。
根据 Vue.js 文档,我尝试将一个模拟传递给 _t 的挂载函数,但没有成功:

const $mocks = { $t: () => {} };
const wrapper = mount(Foo, { localVue, mocks: { $mocks } }) as any;

任何提示将不胜感激。

【问题讨论】:

    标签: typescript vue.js unit-testing jestjs vue-i18n


    【解决方案1】:

    通过讨论这个错误的 Github 问题,我发现 this magic comment by cesalberca:

    “只要它很浅,它就可以工作。如果你安装组件和任何 子组件使用翻译测试将失败 [...]"

    我将mount 替换为shallowMount,现在错误消失了:

    // const wrapper = mount(Foo, { localVue, mocks: { $t: () => {} } }) as any;
    
    const wrapper = shallowMount(Foo, { localVue, mocks: { $t: () => {} } }) as any;
    

    【讨论】:

      猜你喜欢
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 2020-07-11
      • 2019-02-18
      • 1970-01-01
      • 2019-11-24
      相关资源
      最近更新 更多