Notes of Maks Nemisj

Experiments with JavaScript

The place where I WILL use getters in javascript

It’s going to be a short one, but powerful.

Do you remember I wrote previously why getters/setters is a bad idea in JavaScript? I didn’t change my mind, I do still think so, but now I found one valid place where I can and DO want use them. You will never guess. (just kidding)

Unit tests. Nowadays I write unit tests and use getters for testing my code. At appears we have a lot of these else, if statements where boolean values are checked, something like this:

function doSomething(options) {
  if (!options.hasZork) {
  } else if (options.hasBork) {

And this is exactly the place where i can now use getters to test whether hasZork has been checked or not. It helps me to protect my API and ensure that all this eval logical branches are tested:

const sinon = require('sinon');

const hasZork = sinon.spy(() => false);
const hasBork = sinon.spy(() => true);

const options = {
  get hasZork() { return hasZork(); }
  get hasBork() { return hasBork(); }


// assert that both hasZork and hasBork has been called;

I promised you, it will be a short one. The End!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.