我将 Jest 与 Typescript 结合使用。我想创建一个 monorepo。 我的文件夹结构是:
fe
|-app1
|--.jest.config.ts
|--tsconfig.json
|-shared
|--dummyData.ts
我想要来自 app1
的单元测试从 shared
访问一些数据文件夹。
fe/app1/demo.spec.ts
:
import { someData } from '@shared/dummyData' //<--HERE: the alias is works, but jest can not understand "export" keyword
descrube('demo' () => {
it('demo test', () => {
expect(someData).toBe('DUMMY'));
})
})
fe/shared/dummyData.ts
:
export const someData = 'DUMMY';
问题是 jest 会抛出一个错误:
Jest encountered an unexpected token
{"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export const someData = 'DUMMY';
^^^^^^
据我所知,它无法解析由 ts 和 babel 生成的 typescript 或 es6 模块。
它 在 shared
时工作正常文件夹在里面 app1
,但一旦它在外部(和根文件夹外部,例如 '<rootDir>/../shared/$1'
),它就会开始抛出该错误。
这是我的配置:
我在 fe/app1/tsconfig.json
中描述了别名:
{
...
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"paths": {
"@/*": ["app/src/*"],
"@shared/*": ["shared/*"]
}
}
}
并且在 fe/app1/.jest.config.ts
:
module.exports = {
...
transform: {
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
'^.+\\.(jsx?|tsx?)$': 'ts-jest'
},
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'^@shared/(.*)$': '<rootDir>/../shared/$1',
}
}
一些想法:
- 据我所知,我必须告诉 jest 对 rootDir 之外的代码应用相同的解析器(babel 等)。
- 我想可以创建一个
tsconfig
在根文件夹(fe
)中,但我想从fe/app1
启动单元测试文件夹... - 也许可以配置具有
projects
等属性的东西,roots
等等,但到目前为止我运气不好。
最佳答案
好的,我找到了解决方案:
对于 monorepo,将 babel 配置作为 JS 文件很重要
所以,只需将 .babelrc
重命名为 babel.config.js
(在你调用 jest 的文件夹中,在我的例子中是 fe/app1
)
有关更多信息,您可以查看 this comment (可能还有 this thread )
关于javascript - Jest with typescript in monorepo 不适用于根文件夹之外的依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69811333/