I have a Angular Workspace which has a “shared” project. In the shared project I’ve added a simple testService:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TestService {
constructor() { }
public someFunction(): void {
console.log('void')
}
}
I’ve exported the file from my “shared/scr/public.api.ts” file. And imported the TestService in my component:
import { Component, OnInit, inject } from '@angular/core';
import { TestService } from 'shared';
@Component({
selector: 'app-test-flow',
templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
constructor(
private testService: TestService
) {}
ngOnInit(): void {
this.testService.someFunction();
}
}
My spec:
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestService } from 'shared';
describe('AppComponent', () => {
let testService: TestService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
]
});
testService = TestBed.inject(TestService);
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});
When I run a test, I get the error: “Cannot read properties of undefined (reading ‘hasOwnProperty’)”.
app.component.spec.ts (95.998 s)
● AppComponent › should create the app
TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')
20 | });
> 21 | testService = TestBed.inject(TestService);
22 | });
at R3Injector.get (../../node_modules/@angular/core/fesm2022/core.mjs:2279:15)
at _TestBedImpl.inject (../../node_modules/@angular/core/fesm2022/testing.mjs:1573:48)
at Function.inject (../../node_modules/@angular/core/fesm2022/testing.mjs:1444:34)
The error doesn’t show when I don’t import the testService from the shared module.
My jest.config.ts looks like this
import type { Config } from 'jest';
const jestConfig: Config = {
preset: 'jest-preset-angular',
setupFilesAfterEnv: ['<rootDir>/../../setup-jest.ts'],
transform: {
'^.+\.(ts|js|mjs|html|svg)$': [
'jest-preset-angular',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\.(html|svg)$',
},
],
},
transformIgnorePatterns: ['<rootDir>/../../node_modules/'],
moduleNameMapper: {
'^@test/(.*)$': '<rootDir>/../../mocks/unittest/$1/',
'^shared': '<rootDir>/../../dist/shared/index.d.ts/',
},
moduleDirectories: [
'<rootDir>/../../node_modules',
],
};
export default jestConfig;