我有一个用 TypeScript 编写的 Node 项目,它使用 Rollup 作为捆绑器,使用 Jest 作为单元测试框架。它具有以下结构(我省略了我认为与问题无关的内容):
__tests__
greeter.test.ts
config.json
config
template.config.json
src
modules
greeter.ts
index.ts
jest.config.ts
package.json
tsconfig.json
src/index.ts:
import { greeter } from './modules/greeter'
console.log(greeter('Bojan'))
src/modules/greeter.ts:
const config = require('./config.json')
const greeting = config.greeting;
console.log(greeting)
export function greeter(name: string): string {
return greeting + ", " + name
}
__tests__/greeter.test.ts:
import {greeter} from '../src/modules/greeter';
test('greeter uses greeting specifies in the configuration file', () => {
expect(greeter('ABC')).toBe('hi, ABC');
});
test('greeter uses the name specified as its runtime argument', () => {
expect(greeter('ABC')).toContain('ABC');
});
jest.config.js:
module.exports = {
"verbose": true,
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
// "moduleDirectories": [
// "node_modules",
// "<rootDir>/__tests__/"
// ],
// "modulePaths": [
// "<rootDir>/__tests__/"
// ]
};
包.json:
{
...
"main": "index.js",
"scripts": {
"clean": "rm -rf ./build/",
"test": "jest --verbose --coverage --debug --env node",
"build": "npx rollup -c",
"start": "node ./build/app.js"
},
...
"devDependencies": {
"@types/jest": "^24.0.11",
"@types/node": "^11.13.0",
"jest": "^24.7.1",
"rollup": "^1.9.0",
"rollup-plugin-copy": "^1.0.0",
"rollup-plugin-typescript": "^1.0.1",
"ts-jest": "^24.0.2",
"tslib": "^1.9.3",
"typescript": "^3.4.2"
},
"dependencies": {}
}
这个想法是构建创建app.js
包,它读取config.json
应该在同一目录中的配置。
配置.json:
{
"greeting": "hi"
}
套装app.js
包含:
var config = require('./config.json');
...并且运行app.js
正常(config.json
提供时)但是当我运行npm test
(或简单地npx jest
)Jest 错误时:
FAIL __tests__/greeter.test.ts
● Test suite failed to run
Cannot find module './config.json' from 'greeter.ts'
However, Jest was able to find:
'../src/modules/greeter.ts'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].
See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string
> 1 | const config = require('./config.json')
| ^
2 | const greeting = config.greeting;
3 | console.log(greeting)
4 |
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:229:17)
at Object.<anonymous> (src/modules/greeter.ts:1:16)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.03s
Ran all test suites.
为了纠正这个错误,我需要在(in )config.json
旁边保留(仅用于单元测试) ,但我想将它保留在. 我试图更改Jest 配置文件中的moduleDirectories和modulePaths无济于事。greeter.ts
src/modules
__tests__
有没有办法让Jest 测试下config.json
的模块可见,同时在运行时greeter.ts
保持它从包中的可见性app.js
?