【发布时间】:2020-05-04 05:50:23
【问题描述】:
我在服务中有一个带有 setTimeOut 函数的组件。要为此编写单元测试用例,我使用 tick 和 fakeAsync 来设置 TimeOut。但是,它没有被执行。即使我对如何在 if 条件下为 window['MyAirtelAppReact'] 编写测试用例感到好奇。
我已经尝试使用 flushMicrotasks 将清除当前队列中的所有微任务,但不确定这是否是这样做的方法? 我将如何编写单元测试来测试这个?
组件代码:
constructor(
private dataService: DataService,
private loadinSrvc: LoadingService,
private router: Router,
private toastr: ToastrService,
public dialog: MatDialog
){
if (window['MyAirtelAppReact'] !== undefined) {
if (
window['MyAirtelAppReact'] &&
window['MyAirtelAppReact'].getParameters
) {
const deviceInfoString = window['MyAirtelAppReact'].getParameters();
const deviceInfo = JSON.parse(deviceInfoString);
this.dataService.setAppDetails(deviceInfo);
}
} else if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
window['webkit'].messageHandlers.getParameters.postMessage('');
} else {
const deviceInfo = {
channel: 'web',
deviceId: GLOBAL_PROPERTIES.DEVICE_ID,
};
this.dataService.setAppDetails(deviceInfo);
}
this.loadinSrvc.userChangeEvent.subscribe((user) =>
setTimeout(() => {
this.showLoader = {
text: this.loadinSrvc.getLoaderText() || 'Please wait...',
isLoader: user,
};
})
);
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationEnd) {
this.loadinSrvc.setLoader(false);
}
if (event instanceof NavigationStart) {
this.loadinSrvc.setLoader(true);
}
if (event instanceof NavigationError) {
this.toastr.error('Something went wrong, please retry.');
this.loadinSrvc.setLoader(false);
}
});
}
规格文件:
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
ReactiveFormsModule,
RouterTestingModule,
CommonModule,
HttpClientModule,
ToastrModule.forRoot({
timeOut: 3000,
positionClass: 'toast-bottom-right',
maxOpened: 1,
preventDuplicates: true,
}),
MatDialogModule,
],
declarations: [AppComponent],
providers: [
CommonService,
{ provide: DataService, useClass: MockDataService },
],
}).compileComponents();
}));
// try2
it('should test some asynchronous code', fakeAsync(() => {
const fixture = TestBed.createComponent(AppComponent);
const component = fixture.componentInstance;
fixture.detectChanges();
component.showLoader = { isLoader: false, text: 'Please wait...' };
const testObservable = from(Promise.resolve(true));
let flag = false;
testObservable.subscribe((result) => {
flag = true;
});
flushMicrotasks();
expect(flag).toBe(true); // PASSES
}));
});
【问题讨论】:
标签: angular unit-testing angular6 karma-jasmine angular9