Angular2如何测试是否从另一个函数中调用了一个函数

时间:2017-02-03 11:26:38

标签: angular typescript karma-jasmine

在我的模板中,我有一个按钮,用于调用组件内的函数

updateUserProfile(value: any) {
this.dataService.user;
let firstName = value.firstName;
let lastName = value.lastName;
let email = value.email;
let backNumber = value.backNumber;
let position = jQuery('#position').val();
let teamId = jQuery('#team').val();

let user = User.create()
  .setId(this.user.id)
  .setFirstName(firstName)
  .setLastName(lastName)
  .setEmail(email)
  .setBackNumber(backNumber)
  .setPosition(position)
  .setTeamId(teamId)
  .setPassword(this.user.password);
this.user = user;
let currentUserId = LocalStorage.getCurrentUserId();

this.userService.update(currentUserId, user).subscribe(
  data => {
    Materialize.toast("Erfolgreich aktualisiert", 4000);
    this.router.navigate(['/user', currentUserId])
  },
  error => {
    Materialize.toast("Fehler bei der Aktualisierung");
  }
)
}

这是一个名为的函数:

beforeEach(async(() => {
TestBed.configureTestingModule({
  declarations: [EditUserProfileComponent, EditInputFieldComponent],
  imports: [ReactiveFormsModule, NgUploaderModule],
  providers: [
    {provide: UserService, useClass: FakeUserService},
    {provide: DataService, useClass: FakeDataService},
    {provide: TeamService, useClass: FakeTeamService},
    {provide: Router, useClass: FakeRouter},
  ]
})
  .compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(EditUserProfileComponent);
fakeUserService = fixture.debugElement.injector.get(UserService);
fakeDataService = fixture.debugElement.injector.get(DataService);
component = fixture.componentInstance;

fixture.detectChanges();
});



fit('should call the refresh action on Refresh-Button click with the given values',
  fakeAsync(() => {
    spyOn(component, 'updateUserProfile');
    spyOn(fakeUserService, 'update');

    let refreshButtonDebugElement = queryElement('.submit-btn', fixture);
    refreshButtonDebugElement.triggerEventHandler('click', null);

    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(component.updateUserProfile).toHaveBeenCalled(); //evaluates to true
      expect(fakeUserService.update).toHaveBeenCalled(); //throws the error Expected spy update to have been called. 
    });
}));

现在我在测试中找到按钮并在此按钮上触发clickEvent。在click事件之后,我测试是否调用了控制器内的函数(例如udateUserProfile)。该测试评估为真。之后我想检查在updateUserProfile中调用的函数(this.userService.update),但是它的计算结果为false。

这是我的测试:

{{1}}

0 个答案:

没有答案