Vue 给 i18n 国际化组件写单元测试报 $t is not a function

对一个有国际化的 Vue 组件写单元测试,mount这个组件时,会遇到找不到 $t 的报错。

Component template
1
<p>{{ $t('message.hello' }}</p>
1
TypeError: _vm.$t is not a function

Vue 节点上没有 $t,先尝试挂载?

Component.spec.js
1
2
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)

结果会遇到另一个相似的错误。

1
TypeError: Cannot read property '_t' of undefined

我们的 Test Case 不需要测到国际化字符串,那就 mock 一个 $t 好了。

Component.spec.js
1
2
3
4
5
shallowMount(Component, {
methods: {
$t: () => ''
}
})

测试就通过了。

相关插件版本号:

package.json
1
2
3
4
5
6
7
8
{
"dependencies": {
"vue-i18n": "^8.14.1"
},
"devDependencies": {
"@vue/cli-plugin-unit-jest": "^4.1.2",
}
}

Vue 给 i18n 国际化组件写单元测试报 $t is not a function

https://www.imaegoo.com/2020/vue-i18n-unit-test/

作者

iMaeGoo

发布于

2020-01-17

更新于

2020-01-17

许可协议

CC BY 4.0

评论