Как шпионить за функцией, вызываемой внутри объекта класса

Я хочу проверить, вызывается ли this.service.someMethod с помощью jasmine spy.

Исходный файл:

// src.ts
import { Service } from 'some-package';

export class Component {
   service = new Service();

   callMethod() {
      this.service.thatMethod();
   }
}

Файл спецификации:

// src.spec.ts
import { Component } from './src';

describe('test', () => {
   it('calls thatMethod of service', () => {
      let comp = new Component();

      spyOn(comp.service, 'thatMethod').and.callThrough();

      comp.callMethod();

      expect(comp.service.thatMethod).toHaveBeenCalled();
   });
});

Выход:

Неудачный тест: ожидается вызов comp.service.thatMethod.


person Anant_Kumar    schedule 06.05.2020    source источник
comment
Разве comp.thatMethod(); в вашем тесте не должно быть comp.callMethod()?   -  person Mike S.    schedule 06.05.2020


Ответы (1)


Я бы посоветовал вам провести рефакторинг вашего кода и воспользоваться шаблоном IoC (инверсия управления). Это означает, что вам нужно избавиться от Service зависимости в вашем Component классе и ввести ее вручную, например:

export class Component {
   constructor(service) {
       this.service = service;
   }

   callMethod() {
     this.service.thatMethod();
   }
}

// Elsewhere in your code
import { Service } from 'some-package';
const component = new Component(new Service());

Такой подход позволит вам эффективно протестировать компоненты с помощью Service mock:

import { Component } from './src';

describe('test', () => {
    it('calls thatMethod of service', () => {
        const service = jasmine.createSpyObj('service', ['thatMethod']);
        let comp = new Component(service);

        comp.callMethod();
        expect(service.thatMethod).toHaveBeenCalled();
   });
});
person oozywaters    schedule 06.05.2020