如何使用笑话来模拟私有变量

时间:2019-10-27 20:30:42

标签: reactjs typescript unit-testing jestjs

我正在尝试为这样的功能编写单元测试:

export class newClass {
    private service: ServiceToMock;

    constructor () {
    this.service = new ServiceToMock()
    }

    callToTest () {
        this.service.externalCall().then(()=> {
        //Code to test
        })
    }
}

为了测试这段代码,我需要模拟服务,因为它调用了类外部的函数,但是问题是它是私有的。

我该如何精确地嘲笑一个私有变量?该类将创建自己的实例,因此甚至有可能模拟出来吗?

1 个答案:

答案 0 :(得分:0)

在您的实现中,您要么导入服务,要么

implementation.js
import ServiceToMock from './serviceToMock.js';
implementation.spec.js
// import the already mocked service
import ServiceToMock from './serviceToMock.js';
import newClass from './implementation';

// auto-mock the service
jest.mock('./serviceToMock.js');

describe('newClass', () => {
  describe('somMethod', () => {
    beforeAll(() => {
      // it is recommended to make sure
      // the previous calls are cleared
      // before writing assertions
      ServiceToMock.prototype.externalCall.mockClear()

      // jest's auto-mocking will create jest.fn()
      // for each of the service's methods
      // and you will be able to use methods like .mockResolvedValue
      // to modify the mock behavior
      ServiceToMock.prototype.externalCall.mockResolvedValue(data);

      // call your method
      (new newClass).someMethod();
    });

    it('should call ServiceToMock.externalCall', () => {
      // and you can write assertions for the mocked methods
      expect(ServiceToMock.prototype.externalCall).toHaveBeenCalledWith();
    });
  });
});

working example without Types

或者在文件中包含实现

在这种情况下,您必须测试两个类,因为这是您的单元