使用Sinon.JS模拟JavaScript构造函数 [英] Mocking JavaScript constructor with Sinon.JS

查看:341
本文介绍了使用Sinon.JS模拟JavaScript构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to unit test the following 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模拟构造函数以模拟 getEvents internalService 来测试 getData

How do I mock constructor with Sinon.JS in order to mock getEvents of internalService to test getData?

我查看了 Javascript:使用Sinon模拟构造函数但未能提取解决方案。

I looked at Javascript: Mocking Constructor using Sinon but wasn't able to extract a solution.

// 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 (这将不要调用构造函数。)

You can either create a namespace or create a stub instance using sinon.createStubInstance (this will not invoke the constructor).

创建命名空间:

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

这篇关于使用Sinon.JS模拟JavaScript构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆