I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser
variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using component.currentUser = {...}. However, I am encountering failures when running Karma tests. Any help or suggestions would be greatly appreciated.
UserProfileComponent > should create
TypeError: Cannot read property 'id' of null
at UserProfileComponent.ngOnInit (http://localhost:9877/_karma_webpack_/webpack:/src/app/modules/user-profile/page/user-profile/user-profile.component.ts:4:21)
at callHook (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2573:1)
at callHooks (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2542:1)
at executeInitAndCheckHooks (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2493:1)
at refreshView (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9481:1)
at renderComponentOrTemplate (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9580:1)
at tickRootContext (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10811:1)
at detectChangesInRootView (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10836:1)
at RootViewRef.detectChanges (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:22815:1)
at ComponentFixture._tick (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:141:1)
Below is an example of the code.
user-profile.component.ts
ngOnInit(): void {
this.currentUser = this.userService.getUser();
console.log(this.currentUser.id);
this.userAnnouncements();
}
user-profile.component.spec.ts
describe('UserProfileComponent', () => {
let component: UserProfileComponent;
let fixture: ComponentFixture<UserProfileComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HttpClientTestingModule, RouterTestingModule],
declarations: [UserProfileComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(UserProfileComponent);
component = fixture.componentInstance;
component.currentUser = {
id: 1,
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7716131a1e193716131a1e195914181a">[email protected]</a>',
firstname: 'admin',
img_name: 'photo',
lastname: 'admin',
location: 1,
password: 'hashed_pass',
role: 'admin',
username: 'admin',
};
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});