在Jest测试中使用命名的导入内容导入"constants" [英] Importing `constants` in Jest tests with named imports
问题描述
我的项目中有一个config
和constants
文件夹.位于src\config\test.ts
& src\constants\index.js
.
I have a config
and constants
folder in my project. Located in src\config\test.ts
& src\constants\index.js
respectively.
我将Jest设置为使用moduleNameMapper
如下,因此我可以执行import config from 'config'
和import { SOME_CONST } from 'constants'
I've setup Jest to use moduleNameMapper
as below so I can just do import config from 'config'
and import { SOME_CONST } from 'constants'
"moduleNameMapper": {
"config$": "<rootDir>/src/config/test.js",
"constants$": "<rootDir>/src/constants/index.js"
}
但是,在我的测试中,任何使用import { SOME_CONST } from 'constants'
的文件始终会为SOME_CONST
获得undefined
值,而我们默认从config
导出的文件都可以正常工作.
However, in my tests any files which use import { SOME_CONST } from 'constants'
always get an undefined
value for SOME_CONST
whereas any which us the default export from config
work fine.
这是一个已知问题吗?我在这里做错什么了吗?似乎无法将其固定下来.
Is this a known issue? Am I doing something wrong here? can't seem to pin it down.
推荐答案
我遇到了与您相同的问题,但最终发现了这个此评论对我有用,并说要放入您的测试文件:
I was having the same issue as you, but I eventually found this github issue that addresses it. It looks like constants
is a core module and therefore evaluated before jest's module mapping. I found this comment which worked for me and says to put this in your test file:
jest.mock('constants', () => require('path/to/your/constants'))
一种替代方法是执行@dougajmcdonald在他的评论中建议的操作,然后从constants
重命名您的webpack别名去别的东西,例如app-constants
.
An alternative is to do what @dougajmcdonald suggested in his comment above, and rename your webpack alias from constants
to something else, e.g. app-constants
.
这篇关于在Jest测试中使用命名的导入内容导入"constants"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!