使用 Sinon.JS 模拟 JavaScript 构造函数

Mocking JavaScript constructor with Sinon.JS

我想对以下 ES6 进行单元测试 class:

// service.js
const InternalService = require('internal-service');

class Service {
  constructor(args) {
    this.internalService = new InternalService(args);
  }

  getData(args) {   
    let events = this.internalService.getEvents(args);
    let data = getDataFromEvents(events);
    return data;
  }
}

function getDataFromEvents(events) {...}

module.exports = Service;

如何使用 Sinon.JS 模拟构造函数,以便模拟 internalServicegetEvents 来测试 getData

我查看了 Javascript: Mocking Constructor using Sinon 但无法提取解决方案。

// test.js
const chai = require('chai');
const sinon = require('sinon');
const should = chai.should();

let Service = require('service');

describe('Service', function() {
  it('getData', function() {
    // throws: TypeError: Attempted to wrap undefined property Service as function
    sinon.stub(Service, 'Service').returns(0);
  });
});

您可以使用 sinon.createStubInstance 创建命名空间或创建存根实例(这不会调用构造函数)。

创建命名空间:

const namespace = {
  Service: require('./service')
};

describe('Service', function() {
  it('getData', function() {
    sinon.stub(namespace, 'Service').returns(0);
    console.log(new namespace.Service()); // Service {}
  });
});

创建存根实例:

let Service = require('./service');

describe('Service', function() {
  it('getData', function() {
    let stub = sinon.createStubInstance(Service);
    console.log(stub); // Service {}
  });
});