【发布时间】:2018-08-21 22:59:36
【问题描述】:
我正在尝试测试以下功能:
export async function loadLocale(language) {
return await import(`./locales/${language}.json`)
}
使用以下代码:
import * as utils from '@/langs/utils'
describe('language utils to interact with vue-i18n', () => {
it('should load a given locale from file', async () => {
const language = 'es'
expect.assertions(1)
const locale = await utils.loadLocale(language)
expect(locale).toEqual({ foo: 'bar' })
})
})
我已经安装了babel-plugin-dynamic-import-node,因为动态导入在 Node 中不起作用,必须替换为 require。
这是我尝试加载的es.json的内容:
{
"foo": "bar"
}
我的.babelrc 配置如下:
{
"presets": [
"@vue/app"
],
"plugins": [
"syntax-dynamic-import"
],
"env": {
"test": {
"plugins": ["dynamic-import-node"]
}
}
}
这是我的文件夹结构:
│ ├── langs
│ │ ├── i18n.js
│ │ ├── locales # Actual locales
│ │ │ ├── en.json
│ │ │ └── es.json
│ │ └── utils.js
├── tests
│ └── unit
│ ├── langs
│ │ ├── locales # Mocked locales
│ │ │ ├── en.json
│ │ │ └── es.json
│ │ └── utils.spec.js
当我使用 vue-cli 提供的配置时,我尝试使用 --no-cache 标志作为 this answer mentions 运行 Jest。
我得到的错误如下:
Cannot find module 'function () {
return require("./locales/".concat(language, ".json"));
}' from 'utils.js'
11 | }
12 |
> 13 | export async function loadLocale(language) {
14 | return await import(`./locales/${language}.json`)
15 | }
16 |
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:169:17)
at src/langs/utils.js:13:8
这没有意义,因为./locales/es.json 存在!而且,我已经尝试使用与测试中完全相同的路由的 require 并且它正确加载了它的内容。
有什么想法吗?
【问题讨论】:
-
多么奇怪的错误。这听起来像是从字面上获取函数本身的字符串内容(不是
./locales路径),并试图将其作为文件名来查找。 -
@loganfsmyth ????你说得对。这正是正在发生的事情。插件尝试解决已经从
import更改为require的内容
标签: javascript vue.js babeljs jestjs dynamic-import