1

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

出力:

テストに失敗しました: 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());

Serviceこのアプローチにより、モックを使用してコンポーネントを効果的にテストできます。

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 に答える