我正在使用 Angular 7 并尝试编写一些单元测试来涵盖这个简单的组件。
export class DialogComponent implements OnInit {
appError: any;
httpErrorResponse: HttpErrorResponse;
constructor(
public dialogRef: MatDialogRef<DialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {
Eif (data && typeof AppError) {
this.appError = data;
} else {
throw new Error('unknown error type');
}
}
ngOnInit() {
}
navigate(url: string): void {
if (!url) {
throw new Error('url is undefined');
}
window.location.href = url;
}
}
不幸的是,我无法让我的测试用例检查 throw new Error('unknown error type');
和整个 navigate
功能。这是我尝试过的一个示例:这是成功的,但是封面仍未清理干净,这意味着我没有成功。
it('should run #navigate()', async () => {
const dialog = spyOn(component, 'navigate');
component.navigate('http://dummy.com');
expect(dialog).toHaveBeenCalledWith('http://dummy.com');
});
任何指导将不胜感激编辑:AppError
export class AppError {
title?: string;
customMessage?: string;
message?: string;
popUpCloseable: boolean;
navigation?: string;
details?: string;
status?: any;
code?: any;
name?: any;
url?: string;
statusText?: string;
customTextButton?: string;
}
最佳答案
使用 window
时在 Angular 组件中,通常将其作为 WindowRef
注入(inject)。服务。这使您的应用程序更符合依赖注入(inject)的原则,并简化了您的测试。
您可以简单地创建以下包装服务:
import { Injectable } from '@angular/core';
function getWindow (): any {
return window;
}
@Injectable()
export class WindowRefService {
get nativeWindow (): any {
return getWindow();
}
}
至于你的测试,你可以通过beforeEach(() => {
mockWindowRefService = { nativeWindow: {}};
TestBed.configureTestingModule({
providers: [
{ provide: WindowRefService, useValue: mockWindowRefService }
]
});
});
关于Window.Location.Href 的 Angular 单元测试覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65359633/