【问题标题】:Jest spyOn Received number of calls: 0Jest spyOn 接听电话数:0
【发布时间】:2021-02-03 18:45:29
【问题描述】:

我正在为组件编写 Jest 以确保将执行 handleError。

UserService定义为:

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

我在这里删除了大部分不必要的代码。这是我的测试部分。

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

它不起作用,我收到以下错误:

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

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

【问题讨论】:

    标签: angular testing jestjs


    【解决方案1】:

    您的实际 http 请求模拟的返回类型是错误的

    jest.spyOn(httpMock, 'post').mockReturnValue(of(throwError(error)));

    改成

    jest.spyOn(httpMock, 'post').mockReturnValue(throwError(error));

    你预期的断言应该会弹出。

    【讨论】:

    • 然后我得到以下TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    【解决方案2】:

    这里是解决方案;)

    test('should throw an error when login', () => {
          const user = 'user';
          const password = 'password';
          const error = new Error('error');
          const response = {};
    
          jest.spyOn(httpMock, 'post').mockReturnValue(of(throwError(error)));
          const errorSpy = jest.spyOn(errorHandleServiceMock, 'handleError');
    
          try {
            userService.login(user, password).subscribe(() => {
            });
          } catch (e) {
            expect(errorSpy).toHaveBeenCalled();
          }
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2021-03-14
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2012-05-13
      相关资源
      最近更新 更多