vue.js - 如何对使用 nuxt-i18n 的 Vue.js 组件进行单元测试
问题描述
如果我尝试运行下面的东西(使用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);
解决方案
nuxt-i18n 是一个外部库,而不是您自己的代码,因此测试良好实践要求我们仅模拟翻译库及其所需的功能($t
在本例中)。
以下代码应该可以解决您的问题:
describe("SearchField", () => {
const wrapper = mount(SearchField);
it("renders correctly", () => {
mocks: {
$t: (msg) => msg
}
expect(wrapper.element).toMatchSnapshot();
});
});
可以在此处找到有关此方法的更多信息。
推荐阅读
- css - 即使代码正确,为什么我的图像没有加载?
- android - 如何提高 iOS 和 Android 应用程序的网络访问速度?
- java - Selenium 页面模型 - 如何获取属性、提取其内容并在另一个类中使用它
- api - “Lua 不执行原始分配”的含义。在 2.4 中(关于 __newindex)
- performance - Flux.jl 没有利用 julia 中所有可用的线程进行机器学习
- python - 计算一个列表中的项目数在另一个列表中
- r - 如何在 R 中绘制 sigmoidal 数据 - 二进制 Y 连续 X ggplot 混合效应逻辑回归
- powershell - 使用 power shell 中的目录名称属性列出主目录及其子目录
- javascript - 可观察的过滤结果
- python - aws cdk python 无法获取应用程序目标组