如何使用 jest 模拟私有变量

Mat*_*aNg 6 unit-testing typescript reactjs jestjs

我正在尝试为这样的函数编写单元测试:

export class newClass {
    private service: ServiceToMock;

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

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

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

我到底如何用笑话模拟私有变量?该类创建了它自己的实例,那么是否可以模拟出来?

Ten*_*eff 0

在您的实现中,您可以导入服务

implementation.js
import ServiceToMock from './serviceToMock.js';
Run Code Online (Sandbox Code Playgroud) 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();
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

没有类型的工作示例

或者在文件中有实现

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