Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  102] [ 7]  / answers: 1 / hits: 24930  / 8 Years ago, wed, october 26, 2016, 12:00:00

I'm trying to stub out a super call with sinon, and es2016 but I'm not having much luck. Any ideas why this isn't working?



Running Node 6.2.2, this might be an issue with its implementation of classes/constructors.



.babelrc file:



{
presets: [
es2016
],
plugins: [
transform-es2015-modules-commonjs,
transform-async-to-generator
]
}


Test:



import sinon from 'sinon';

class Foo {
constructor(message) {
console.log(message)
}
}

class Bar extends Foo {
constructor() {
super('test');
}
}

describe('Example', () => {
it('should stub super.constructor call', () => {
sinon.stub(Foo.prototype, 'constructor');

new Bar();

sinon.assert.calledOnce(Foo.prototype.constructor);
});
});


Result:



test
AssertError: expected constructor to be called once but was called 0 times
at Object.fail (node_modulessinonlibsinonassert.js:110:29)
at failAssertion (node_modulessinonlibsinonassert.js:69:24)
at Object.assert.(anonymous function) [as calledOnce] (node_modulessinonlibsinonassert.js:94:21)
at Context.it (/test/classtest.spec.js:21:18)


Note: this issue seems to only happen for constructors. I can spy on methods inherited from the parent class without any issues.


More From » node.js

 Answers
4

You'll need to setPrototypeOf the subClass due to the way JavaScript implements inheritance.



const sinon = require(sinon);

class Foo {
constructor(message) {
console.log(message);
}
}

class Bar extends Foo {
constructor() {
super('test');
}
}

describe('Example', () => {
it('should stub super.constructor call', () => {
const stub = sinon.stub().callsFake();
Object.setPrototypeOf(Bar, stub);

new Bar();

sinon.assert.calledOnce(stub);
});
});

[#60267] Monday, October 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
koltenb

Total Points: 276
Total Questions: 92
Total Answers: 101

Location: North Korea
Member since Fri, Nov 4, 2022
2 Years ago
;