gpt4 book ai didi

javascript - 无法使用 Jest 和 babel-plugin-dynamic-import-node 测试动态导入的函数

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:31 25 4
gpt4 key购买 nike

我正在尝试测试以下功能:

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 标志运行 Jest 作为 this answer mentions .

我得到的错误如下:

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 和测试中完全相同的路径,它正确加载了它的内容。

有什么想法吗?

最佳答案

您使用了两次 dynamic-import-node 插件。我对

做了同样的事情
"presets": [
"react-app",
],

参见 vue-cli/packages/@vue/babel-preset-app/index.js

关于javascript - 无法使用 Jest 和 babel-plugin-dynamic-import-node 测试动态导入的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49260386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com