【问题标题】:Cannot spy the getNotification() property because it is not a function; undefined given instead无法窥探 getNotification() 属性,因为它不是函数;给定的未定义
【发布时间】:2021-07-05 22:01:17
【问题描述】:

我在 Angular 测试用例的 jest spyOn 中遇到了这个错误。 getNotification 是文件中定义的私有方法。这是编写的测试用例:

    const errorSpy = jest.spyOn(service as any, 'getNotification');
    const spy = jest
  .spyOn(service, 'func')
  .mockReturnValue(throwError('error'));
actions$ = of(abc);
effects.abc$.subscribe((res) => {
  expect(errorSpy).toHaveBeenCalled();
  expect(res).toEqual(funcFail({ error: 'error' }));
  expect(spy).toHaveBeenCalledTimes(1);
  done();

【问题讨论】:

    标签: angular typescript jestjs karma-jasmine


    【解决方案1】:

    由于函数是私有的,你不能直接访问它。所以改为使用prototype 来访问该函数:

    const errorSpy = jest.spyOn(service.prototype as any, 'getNotification');
    

    这是一个相关的帖子:https://stackoverflow.com/a/56045577/10781739

    【讨论】:

      猜你喜欢
      • 2020-06-11
      • 2020-09-04
      • 2021-11-02
      • 1970-01-01
      • 2020-10-30
      • 2020-12-06
      • 1970-01-01
      • 2022-01-08
      • 2022-11-29
      相关资源
      最近更新 更多