1

我想测试是否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 已被调用。

4

1 回答 1

2

我建议您重构代码并利用 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());

这种方法将允许您使用Servicemock 有效地测试您的组件:

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();
   });
});
于 2020-05-06T09:30:48.327 回答