configuration data and mocha unit testing

25 views
Skip to first unread message

Wayne Rasmussen

unread,
Feb 1, 2018, 5:29:49 PM2/1/18
to Mocha
In the book Maintainable JavaScarip by Nicholas Zakas, he talks about externalizing configuration data in chapter 9.

He gives an example like this:
var config = {
MSG_INVALID_VALUE: "Invalid value",
URL_INVALID: "/errors/invalid.php",
CSS_SELECTED: "selected"
};

But my question in general is "IF I go this route by whatever means" how do I deal with configuration variations for unit testing?

You might have a SORT_BY: with values { "ID", "LastName", "Record_Type", "Date"} or some such thing.

So if we are going to run some tests, we want to test against each of those values.   NOTE:  I know some of you are pedantic about such example
and it might be a horrible example from off the top of head.  So if you have an issue with that, please just keep  it to yourself and focus on the general
concept/approach.

Vlad GURDIGA

unread,
Feb 2, 2018, 2:02:47 AM2/2/18
to Mocha
Hey Wayne! 👋

I’d look into injecting the configuration data. Maybe something like this:

// production code
function worker(configData) {
  var result = {};

  // populate result taking into account configData

  return result;
}

// test code

describe('worker', function() {
  var result;
  var configData = {...};

  context('when host is local host', function() {
    beforeEach(function() {
      configData.host = 'localhost';
      result = worker(configData);
    });

    it('it does something special', function() {
      expect(result).to.contain(theSpecialBit);
    });
  });
});

Do you think some variation of this would work for your context? 🤔

Wayne Rasmussen

unread,
Feb 2, 2018, 2:38:39 PM2/2/18
to Mocha
Yes, we can always pass something in like that.  Programming 101.  Sorry I didn't spell it out with more detail.  Is there anything in Mocha that allows perhaps another way to do this without injecting?  AKA:  What is the standard Mocha way?  I don't see anything in the Mocha docs regarding this.

Vlad GURDIGA

unread,
Feb 3, 2018, 5:38:14 AM2/3/18
to moc...@googlegroups.com
Um… I’m not aware about anything like that. 🤔

Vlad GURDIGA

unread,
Feb 3, 2018, 5:42:50 AM2/3/18
to moc...@googlegroups.com
…I mean Mocha is just the framework to organize and run test code. It is not concerned about dependency injection. 🤓
Reply all
Reply to author
Forward
0 new messages