【发布时间】:2019-10-04 08:41:14
【问题描述】:
我正在为 Angular 应用程序编写单元测试。我想测试 router.navigate 是否将我带到正确的位置。
当 API 响应成功时,router.navigate 会转到不同的位置。但测试失败,“预期间谍导航已被 ['accounts'] 调用,但从未被调用。”
AccountsListComponent.ts
deleteRecord(id) {
this.http.delete('/api/accounts/' + id)
.subscribe(res => {
if (res['status'] == "FAILURE") {
console.log("failure");
} else {
console.log("API responded success"); //this is printed
this.router.navigate([ '/accounts' ]); // I want to test this
}
}, (err) => {
console.log(err);
}
);
}
component.spec.ts
routerStub = {
navigate: jasmine.createSpy('navigate'),
};
TestBed.configureTestingModule({
imports:[RouterTestingModule,FormsModule,ReactiveFormsModule,HttpClientTestingModule,RouterTestingModule.withRoutes([{ path: 'accountsList', component: AccountsListComponent}])],
declarations: [ AccountDetailComponent,AccountsListComponent ],
schemas:[CUSTOM_ELEMENTS_SCHEMA]
})
it ('should delete account, if account exist and take back to accountsList page', ()=> {
let spyOnDelete = spyOn (component,'deleteRecord').and.callThrough();
fixture.detectChanges();
component.record.AccountID = "account";
fixture.detectChanges();
let deleteButtonDOM = fixture.debugElement.query(By.css('#deletebtn'));
deleteButtonDOM.triggerEventHandler('click',null);
fixture.detectChanges();
expect(spyOnDelete).toHaveBeenCalled(); //passes
const req = _HttpTestingController.expectOne('/api/accounts/'+ component.record.AccountID);
expect(req.request.method).toBe("DELETE");
req.flush({status:"SUCCESS"});
expect(routerStub.navigate).toHaveBeenCalledWith('accounts');//fails???
})
【问题讨论】:
-
我的问题的答案在这里stackoverflow.com/questions/39791773/…
标签: angular typescript unit-testing