首页 > 解决方案 > Angular Jasmin ObjectSpy 不是函数

问题描述

每当在任何测试中调用服务时,我都会尝试监视服务,因此创建一个模拟:

import { SpyObject } from './spyobject';
import { TranslateService } from '@ngx-translate/core';

export class MockTranslateService extends SpyObject {

  constructor() {
    super(TranslateService);
    this.spy('instant').andReturn('');
  }
}

我这样提供:

    {
      provide: TranslateService,
      useValue: MockTranslateService,
    },

我的组件使用this.translateService.instant并获得:TypeError: this.translateService.instant is not a function.

另一方面,当我在组件中记录 translateService 时,我得到:

class MockTranslateService extends spyobject_1.SpyObject {
          constructor() {
              super(core_1.TranslateService);
              this.spy('instant').andReturn(this);
          }
      }

知道为什么间谍不工作吗?提前致谢。

标签: angularjasminemocking

解决方案


为了this.spy('instant')工作,您需要一个监视功能。这将起作用:

export class MockTranslateService extends SpyObject {
  constructor() {
    super(TranslateService);
    this.spy('instant').andReturn('');
  }

  public instant() { }
}

由于该instant函数已定义,因此可以添加间谍。


编辑这可能更容易。在一个beforeEach块中,执行以下操作:

beforeEach(() => {
  spyOn(TranslateService.prototype, 'instant');
});

这会将间谍直接放在原型上,并在每次测试后对其进行清理。


推荐阅读