我在带有Rollup的项目中使用vanilla javascript。我正在使用并且我第一次安装了 Jest,在对我的问题进行了一些研究后,我有一个基本的设置:
// jest.config.js
module.exports = {
coverageDirectory: 'coverage',
moduleFileExtensions: ['js'],
moduleNameMapper: {
'^applicationRoot/(.*)$': '<rootDir>/src/$1',
},
};
我正在使用rollup-plugin-alias库,这是我的rollup.config中的一个示例.js
// rollup.config.js
// ...
alias({
resolve: ['.js'],
applicationRoot: __dirname + '/src',
entries: [
{
find: 'global/http',
replacement: `${__dirname}/src/global/http/index.js`,
},
]})
我库中的所有类都驻留在./src 目录中。如果在我的输入文件 (./src/index.js( 中,我有以下行:
// ./src/index.js
import Http from 'global/http';
export class MyClass {
}
在我的测试文件中,我有:
// ./src/index.spec.js
import { MyClass } from './index';
在终端中,我收到以下错误:
● Test suite failed to run
Cannot find module 'global/http' from 'src/index.js'
Require stack:
src/index.js
src/index.spec.js
> 1 | import Http from 'global/http';
我还应该做什么?感谢您的任何帮助或评论。
[已编辑]
我创建了一个虚拟存储库,其结构类似于上述结构:
https://github.com/luenmuvel/dummy-project-rollup-jest-issues
在这种情况下,他们所要做的就是克隆项目并运行">npm i"或">yarn"。
在浏览器中,它确实有效: 你只需要运行:
- ">npm runbuild"或">yarn build">
- 请参阅浏览器终端中的输出。
开玩笑是行不通的。 你只需要运行: - ">npm runt"或">yarn t" -等待输出。
据我所知,问题是在您的.spec
文件中,您正在导入原始文件,而不是编译的文件。
编译的文件是一个汇总输出,具体取决于您的输出选项。例如,以下是配置它的方式:
output: {
file: "dist/bundle.js",
format: "umd",
name: "testing",
},
构建的文件位于dist/bundle.js
,但在您的.spec
文件中,您像这样导入它:
import MyClass from "./index";
不仅如此,您还使用了一些插件,这些插件对最终输出有影响。
不确定这种比较是否正确,但就像您想从JS
文件导入TS
文件一样。你会犯的错误是一样的。
另请注意,index
没有默认导出:
export class MyClass { }
我想出的解决方案是使用开玩笑的moduleNameMapper
选项将index.js
映射到汇总输出的文件:
// jest.config.js
module.exports = {
coverageDirectory: "coverage",
moduleFileExtensions: ["js"],
moduleNameMapper: {
"^applicationRoot/(.*)$": "<rootDir>/src/$1",
},
moduleNameMapper: {
"./index.js": "../dest/bundle.js"
}
};
spec
文件将像这样导入文件:
import { MyClass } from './index.js';