如何监视 class 对象内部调用的函数

How to spy on a function called inside class object

我想测试是否使用 jasmine spy 调用 this.service.someMethod

源文件:

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

输出:

Failed test: Expected comp.service.thatMethod to have been called.

我建议您重构代码并利用 IoC(控制反转)模式。这意味着您必须摆脱 Component class 中的 Service 依赖项并手动注入它,如下所示:

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