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

krl*_*krl 25 javascript unit-testing mocking node.js sinon

我想对下面的ES6类进行单元测试:

// 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;
Run Code Online (Sandbox Code Playgroud)

我如何嘲笑与Sinon.JS构造,以模拟getEventsinternalService测试getData

我查看了使用Sinon的Javascript:Mocking Constructor,但无法提取解决方案.

// 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);
  });
});
Run Code Online (Sandbox Code Playgroud)

vic*_*ohl 23

您可以使用创建命名空间或创建存根实例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 {}
  });
});
Run Code Online (Sandbox Code Playgroud)

创建存根实例:

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

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