【问题标题】:How to unit test Vue.js components that use nuxt-i18n如何对使用 nuxt-i18n 的 Vue.js 组件进行单元测试
【发布时间】: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: () => {} }. })

标签: vue.js jestjs nuxt.js nuxt-i18n


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    相关资源
    最近更新 更多