I have Angular projects with Jest in place for unit testing. I'm trying to unit test a certain service that has environment variable as private property and if I run the test, it fails with the following information - Cannot find module 'src/environments/environment' from 'src/app/resources/services/resources.service.ts'
FAIL src/app/resources/services/resources.service.test.ts
● Test suite failed to run
Cannot find module 'src/environments/environment' from 'src/app/resources/services/resources.service.ts'
Require stack:
src/app/resources/services/resources.service.ts
src/app/resources/services/resources.service.test.ts
1 | import { Injectable } from '@angular/core';
> 2 | import { environment } from 'src/environments/environment';
| ^
3 | import { Observable, Subject } from 'rxjs';
4 | import { Resource } from '../models/resources';
5 | import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:427:11)
at Object.<anonymous> (src/app/resources/services/resources.service.ts:2:1)
at Object.<anonymous> (src/app/resources/services/resources.service.test.ts:7:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 3.484 s
jest.config.ts
// require('jest-preset-angular/ngcc-jest-processor');
globalThis.ngJest = {
skipNgcc: true,
tsconfig: 'tsconfig.spec.json', // this is the project root tsconfig
};
/** @type {import('@jest/types').Config.InitialOptions} */
module.exports = {
preset: 'jest-preset-angular',
setupFiles: ['<rootDir>/src/environment/environment'],
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
};
setupJest.ts
import 'jest-preset-angular/setup-jest';
import './jest-global-mocks';
Any help will be much appreciated.
CodePudding user response:
The path should be relative as pointed out by @e-maggini