[英]Mocking JavaScript constructor with Sinon.JS
我想對下面的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模擬構造函數以模擬internalService
getEvents
來測試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);
});
});
您可以使用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 {}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.