0

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

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(或在第二次测试中返回错误)。所以我希望我的测试看起来像这样:

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

1 回答 1

0

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

棘手的部分是,如果您没有该类的实例,则需要在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);
});

您可以在此处找到一个工作示例 。

于 2019-02-14T12:52:01.510 回答