I'm trying to spy on service whenever it's called on any test, so a create a mock:

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

export class MockTranslateService extends SpyObject {

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

I provide it like this:

    {
      provide: TranslateService,
      useValue: MockTranslateService,
    },

My component uses this.translateService.instant and gets: TypeError: this.translateService.instant is not a function.

On the other hand, when I log translateService in my component I get:

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

any idea why the spy is not working? thanks in advance.

2 Answers

0
user1928596 On Best Solutions

The problem was in the way I provided the mock in the test config, it should have been like this:

    {
      provide: TranslateService,
      useValue: new MockTranslateService(),
    },

I don't fully understand why, sometimes the other syntax work and sometimes not, I think it has to do with how Typescript handle types.

0
Andrew Eisenberg On

In order for this.spy('instant') to work, you need a function to spy on. This will work:

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

  public instant() { }
}

Since the instant function is already defined, the spy can be added.


EDIT This might be easier. In a beforeEach block, do the following:

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

This places the spy directly on the prototype and it gets cleaned up after each test.