我正在为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???
})
答案 0 :(得分:0)
您正在监视函数deleteRecord,这意味着该调用将在不执行该函数的情况下进行。您不应监视正在测试的功能,而应监视http.delete()函数。