我正在为我的 Angular 应用程序编写组件单元测试。currentUser我在组件和 html 模板中使用了一个变量。每次测试都会对其进行模拟(通过component.currentUser = {...}进行硬编码)。无论如何,业力失败了。将不胜感激任何帮助。
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)
Run Code Online (Sandbox Code Playgroud)
下面的代码示例。
用户配置文件.component.ts
ngOnInit(): void {
this.currentUser = this.userService.getUser();
console.log(this.currentUser.id);
this.userAnnouncements();
}
Run Code Online (Sandbox Code Playgroud)
用户配置文件.组件.规格.ts
describe('UserProfileComponent', () => {
let component: UserProfileComponent;
let fixture: ComponentFixture<UserProfileComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({ …Run Code Online (Sandbox Code Playgroud)