Reputation: 23
I've tsconfig.json file in which I mapped all my paths eg
{
"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/*"]
}
}
}
And I have a file called form.ts in which I have code below.
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();
}
}
It all works great when compiling typescript, however as I am running tests for this class eg->
import { FormComponent } from '../../ui/components/form';
describe('Form class test', () => {
test('It should have a method called getForm', () => {
expect(new FormComponent().getForm).toBeInstanceOf(Function);
});
});
It failed with an error Cannot find module '@decorators/component' from 'ui/components/form.ts' at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:491:11) at Object. (ui/components/form.ts:1:1)
I know that it's because of the path mappings in tsconfig.json and it only works on compilation of code, It looks like jest can't resolve those path mappings in my form.ts file, Btw it's raw typescript code no libraries or frameworks, So is there any way to solve this? without throwing away all those path mappings and revert to long imports?
Upvotes: 1
Views: 1511
Reputation: 11250
I use the TS-Jest plugin to add this support, and then the paths are in your tsconfig.json file.
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: './',
...
};
Then the paths defined in your tsconfig.json will work in the tests.
{
"compilerOptions": {
"module": "commonjs",
...
"paths": {
"@LIBRARY/*": [
"./src/library/*"
],
"@TEST_LIBRARY/*": [
"./test/library/*"
],
"@APP/*": [
"./src/*"
]
}
}
Upvotes: 1