【发布时间】: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