mardi 2 février 2021

Jest spyOn Received number of calls: 0

I am writing Jest for the components to make sure that handleError will be executed.

The UserService is defined as:

export class UserService {

  constructor(private http: HttpClient, private errorHandleService: ErrorHandlerService) {
  }

  login(user, password) {
    this.loadingLogin.next(true);
    return this.http.post(this.loginUrl, JSON.stringify({
      user,
      password
    }), this.httpOptions)
      .pipe(
        catchError(error => this.errorHandleService.handleError('login', error)),
        finalize(() => this.loadingLogin.next(false))
      );
  }
}

I have removed most of unnecessary code here. Here is my testing part.

describe('UserService', () => {
  let httpMock;
  let errorHandleServiceMock;
  let userService;

  beforeEach(() => {
    httpMock = {
      post: jest.fn()
    };

    errorHandleServiceMock = {
      handleError: jest.fn()
    };

    userService = new UserService(httpMock, errorHandleServiceMock);
  });
  afterEach(() => {
    jest.clearAllMocks();
  });

  describe('Login', () => {
    test('should throw an error when login', () => {
      const user = 'user';
      const password = 'password';
      const error = 'error';
      const response = {};

      jest.spyOn(httpMock, 'post').mockReturnValue(of(throwError(error)));
      const errorSpy = jest.spyOn(errorHandleServiceMock, 'handleError');

      userService.login(user, password).subscribe(() => {
      });

      expect(errorSpy).toHaveBeenCalled();
    });
  });

It isn't working and I got the following error:

Error: expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

Aucun commentaire:

Enregistrer un commentaire