簡體   English   中英

如何監視在 class object 內部調用的 function

[英]How to spy on a function called inside class object

我想測試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();
   });
});

Output:

測試失敗:預期 comp.service.thatMethod 已被調用。

我建議您重構代碼並利用 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();
   });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM