【问题标题】:How to spy on a function called inside class object如何监视类对象内部调用的函数
【发布时间】:2020-05-06 08:40:22
【问题描述】:

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

【问题讨论】:

  • 你的测试中的comp.thatMethod();不应该是comp.callMethod()吗?

标签: javascript typescript unit-testing jasmine spyon


【解决方案1】:

我建议您重构代码并利用 IoC(控制反转)模式。这意味着您必须在 Component 类中摆脱 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();
   });
});

【讨论】:

    猜你喜欢
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2017-12-04
    • 2010-10-27
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多