开玩笑无法解析路径映射并抛出模块未找到错误



我有tsconfig.json文件,我在其中映射了所有路径,例如

{
"compilerOptions": {
"lib": ["es2015", "dom"],
"target": "es2015",
"baseUrl": ".",
"types": ["reflect-metadata", "jest", "node", "@types/jest"],
"typeRoots": ["./types", "./node_modules/@types"],
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"paths": {
"@utils/*": ["./utils/*"],
"@helpers/*": ["./ui/helpers/*"],
"@domElements/*": ["./core/dom/*"],
"@networking/*": ["./networking/*"],
"@components/*": ["./ui/components/*"],
"@decorators/*": ["./core/decorators/*"],
"@eventFunctions/*": ["./ui/event functions/*"]
}
}
}

我有一个名为form.ts的文件,其中有下面的代码。

import { component } from '@decorators/component';
import { event } from '@decorators/events';
import { DOMElements } from '@domElements/domElements';
import { submitForm } from '@eventFunctions/formSubmit';
@component
export class FormComponent {
@event('submit', submitForm)
getForm(): HTMLDivElement {
return DOMElements.getForm();
}
}

编译typescript时一切都很好,然而,当我为这个类运行测试时,例如->

import { FormComponent } from '../../ui/components/form';
describe('Form class test', () => {
test('It should have a method called getForm', () => {
expect(new FormComponent().getForm).toBeInstanceOf(Function);
});
});

它失败,返回错误。无法从"ui/components/form.ts"中找到模块"@decorators/component"在Resolver_throwModNotFoundError(node_modules/jest-resolve/build/resolver.js:491:11(在对象处。(ui/组件/表单.ts:1:1(

我知道这是因为tsconfig.json中的路径映射,它只适用于代码的编译,看起来jest无法解决我的form.ts文件中的那些路径映射,顺便说一句,这是原始的typescript代码,没有库或框架,所以有什么方法可以解决这个问题吗?而不丢弃所有这些路径映射并恢复到长导入?

我使用TS Jest插件来添加这种支持,然后路径在tsconfig.json文件中。

const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig); // This adds the support
module.exports = {
moduleNameMapper,
preset: 'ts-jest',
testEnvironment: 'node',
rootDir: './',
...
};

然后,tsconfig.json中定义的路径将在测试中起作用。

{
"compilerOptions": {
"module": "commonjs",
...
"paths": {
"@LIBRARY/*": [
"./src/library/*"
],
"@TEST_LIBRARY/*": [
"./test/library/*"
],
"@APP/*": [
"./src/*"
]
}
}

相关内容

  • 没有找到相关文章

最新更新