如何对使用 nuxt-i18n 的 Vue.js 组件进行单元测试

Posted

技术标签:

【中文标题】如何对使用 nuxt-i18n 的 Vue.js 组件进行单元测试【英文标题】:How to unit test Vue.js components that use nuxt-i18n 【发布时间】:2019-06-26 03:19:30 【问题描述】:

如果我尝试运行下面的东西(使用yarn run jest),我会得到 TypeError: _vm.$t is not a function,因为SearchField 正在使用翻译("$t('search')" )。

import  mount  from "@vue/test-utils";
import SearchField from "@/components/ui/SearchField";

describe("SearchField", () => 
  const wrapper = mount(SearchField);

  it("renders correctly", () => 
    expect(wrapper.element).toMatchSnapshot();
  );
);

如果我在开头添加以下三行,我会得到 TypeError: Cannot read property '_t' of undefined

import Vue from "vue";
import VueI18n from "vue-i18n";
Vue.use(VueI18n);

【问题讨论】:

你应该为$t 提供模拟 - 类似mount(SearchField, mocks: $t: () => . ) 【参考方案1】:

nuxt-i18n 是一个外部库,而不是您自己的代码,因此测试良好实践要求我们只模拟翻译库及其所需的功能(在本例中为$t)。

以下代码应该可以解决您的问题:

describe("SearchField", () => 
  const wrapper = mount(SearchField);

  it("renders correctly", () => 
    mocks: 
      $t: (msg) => msg
    
    expect(wrapper.element).toMatchSnapshot();
  );
);

有关此方法的更多信息,请访问here。

【讨论】:

以上是关于如何对使用 nuxt-i18n 的 Vue.js 组件进行单元测试的主要内容,如果未能解决你的问题,请参考以下文章