0

I am writing unit test for Angular app. I want to test if router.navigate is taking me to correct location or not .

When API responds success router.navigate takes to different location. But the test fails with 'Expected spy navigate to have been called with [ 'accounts' ] but it was never called.'

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???

  }) 

karansys
  • 2,449
  • 7
  • 40
  • 78
  • Answer to my question is here https://stackoverflow.com/questions/39791773/angular-2-4-6-7-unit-testing-with-router – karansys Oct 04 '19 at 08:46

1 Answers1

0

You are spying on your function deleteRecord, that means the call will go through without executing the function. You should not spy on the function you are testing, rather you should spy on http.delete() function.

Akshay Rana
  • 1,455
  • 11
  • 20