Skip to content

Instantly share code, notes, and snippets.

View gagarwa's full-sized avatar
🎯
Focusing

Gitesh Agarwal gagarwa

🎯
Focusing
View GitHub Profile
@tswaters
tswaters / stubbing-classes.md
Last active June 18, 2024 12:47
stubbing classes?

Stubbing Classes and their Constructors in Native ES6

It's getting to that point. All the major evergreen browsers have (mostly) functional class keyword. But what does this mean for unit tests and the ability to stub constructors? In short, the answer is 'no'.

Many will tell you that es6 classes are just sugar coated es5 functions with prototypal inheritance setup. Mostly true - but there are two considerations that make testing more difficult:

  • super is a magical keyword that calls the same method on the parent class. in cases with methods, easy enough to stub those, sinon.stub(parent.prototype, 'whatever') -- for super itself, there is no way to stub out the constructor call... normally not a huge deal, but...

  • classes are not added to the global scope. where once you could call sinon.stub(global, 'SomeFunction'), sinon.stub(global, 'SomeClass') (or under window in the browser), this will throw an error.