【问题标题】:Mock helper classes in jasmine unit test茉莉花单元测试中的模拟助手类
【发布时间】:2019-02-14 11:28:36
【问题描述】:

我想对使用辅助类的角度组件进行单元测试。辅助类及其函数不应成为此测试的一部分,而应被模拟。 该组件可能如下所示:

import { MyHelperClass } from "./my-helper-class";

export class MyComponent {
    public doStuff() {
        const helper = new MyHelperClass();
        if (helper.check()) {
            // code I want to test
        }
    }
}

我想将helper.check() 的功能排除在单元测试之外,并假设它返回true(或在第二次测试中返回false)。所以我希望我的测试看起来像这样:

it("#doStuff should do something, assuming helper.check() is true, () => {
    // make constructor of MyHelperClass return a Mock
    // (or somehow spy on helper.check() and return true?) 

    expect(component.doStuff()).toBe(someValue);
});

【问题讨论】:

    标签: angular unit-testing jasmine testbed


    【解决方案1】:

    您可以设置一个间谍来模拟函数调用并为check() 返回您想要的任何值。它还可以让您检查该函数是否被调用(例如,spy 是否被实际调用以及调用了多少次等)。

    棘手的部分是,如果您没有该类的实例,则需要在您的类的 prototype 上设置您的间谍。

    看看这段代码(dummyVariable只是一个变量,用来测试check()之后的代码是否被执行):

    it('doStuff should do something, assuming helper.check() is true', () => {
      // test the before value
      expect(component.dummyVariable).toBe(false);
    
      // set up the spy and make it return true
      const spy = spyOn(MyHelperClass.prototype, 'check').and.returnValue(true);
    
      // call our function
      component.doStuff();
    
      // check the after value
      expect(component.dummyVariable).toBe(true);
    
      // check if our spy/mocked function was actually called
      expect(spy).toHaveBeenCalledTimes(1);
    });
    
    // same thing as above but this time our spy returns false
    it('doStuff should do something, assuming helper.check() is false', () => {
      expect(component.dummyVariable).toBe(false);
    
      const spy = spyOn(MyHelperClass.prototype, 'check').and.returnValue(false);
      component.doStuff();
    
      expect(component.dummyVariable).toBe(false);
      expect(spy).toHaveBeenCalledTimes(1);
    });
    

    您可以找到一个工作示例 here.

    【讨论】:

    • 非常感谢!窥探原型的技巧正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多