首页 > 解决方案 > 如何测试 expect().toHaveBeenCalled() - Angular2+

问题描述

我想测试我的外部函数是否已被调用,但我似乎没有弄清楚......

我目前收到失败消息:

预期的间谍登录已被调用。

测试

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;
          }
      );
    }

标签: javascriptangular

解决方案


尝试这个:

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

这是 Angular 5+ 的一个很好的测试指南:https ://codecraft.tv/courses/angular/unit-testing/mocks-and-sies/


推荐阅读