如何测试Expect()。toHaveBeenCalled()-Angular2 +

时间:2018-07-25 14:35:21

标签: javascript angular

我想测试我的外部函数是否已被调用,但我似乎不知道...

我当前收到失败消息:

  

预期已调用间谍登录。

测试

fit('should login with valid form & credentials', inject([AuthService],
        (authServ: AuthService) => {
        component.onSubmit(validFormGoodCreds);
        spy = spyOn(authServ, 'login');

        expect(spy).toHaveBeenCalled();
        expect(hideMsg).toEqual(true);
    }));

登录组件

...
onSubmit(form: NgForm) {
    if (form.valid) {
      this.authService.login(this.user.username, this.user.password)
      .subscribe(
          data => {
            /* TODO: Navigate to holding page etc */
            // Hide any error message that was previously shown
            this.hideErrorMsg = true;
          },
          err => {
            // Change error message to be shown
            this.errorMessage = 'Either username or password were incorrect';
            // Show the error message
            this.hideErrorMsg = false;
          }
      );
    }

1 个答案:

答案 0 :(得分:0)

尝试一下:

spy = spyOn(authServ, 'login').and.returnValue(true); 
expect(authServ.login).toHaveBeenCalled(); 

这是针对Angular 5+的良好测试指南:https://codecraft.tv/courses/angular/unit-testing/mocks-and-spies/