I'm trying to test Angular components with jest via jest-preset-angular
it can run the test by karma
with ng test
,
but running the same test by jest
gives the error
AppComponent › should create the app
Component 'AppComponent' is not resolved:
- templateUrl: ./app.component.html
- styleUrls: ["./app.component.scss"]
Did you run and wait for 'resolveComponentResources()'?
1- generate a new angular project ng new myproject
2- install jest dependencies
3- create jest config file
4- copy and modify src/app/app.component.spec.ts
to app.component.spec.jest.ts
to test app.component.spec.ts
file by karma run npm t
or ng test
and then run npm run test:jest
to test app.component.spec.jest.ts
by jest
The problem is detailed here: https://github.com/thymikee/jest-preset-angular/issues/951
For my part it worked when I added the following in jest.config.js
:
module.exports = {
transform: {
'^.+\\.(ts|js|html)$': 'jest-preset-angular'
},
};
They also suggest setting up this in jest.preset.js
, but that wasn't necessary for me...
const nxPreset = require('@nrwl/jest/preset');
module.exports = {
...nxPreset,
testEnvironment: 'jsdom',
transform: {
'^.+\\.(ts|js|html)$': 'jest-preset-angular'
}
};