用 Sinon.JS 模拟 JavaScript 构造函数

编程入门 行业动态 更新时间:2024-10-04 05:32:52

用 Sinon.JS 模拟 JavaScript 构造<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数"/>

用 Sinon.JS 模拟 JavaScript 构造函数

我想对以下 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;

如何使用 Sinon.JS 模拟构造函数以模拟

getEvents
internalService
以测试
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 {}
  });
});

更多推荐

用 Sinon.JS 模拟 JavaScript 构造函数

本文发布于:2024-05-30 22:00:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   Sinon   JS   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!