【问题标题】:Expected spy navigate to have been called with [ 'accounts' ] but it was never called预期的间谍导航已使用 ['accounts'] 调用,但从未调用过
【发布时间】: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???

  }) 

【问题讨论】:

标签: angular typescript unit-testing


【解决方案1】:

您正在监视您的函数 deleteRecord,这意味着调用将通过而不执行该函数。你不应该监视你正在测试的函数,而应该监视 http.delete() 函数。

【讨论】:

    猜你喜欢
    • 2020-08-20
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 2023-03-24
    • 2017-11-18
    • 1970-01-01
    • 2019-02-05
    相关资源
    最近更新 更多