samedi 23 mai 2015

How do I - and should I - spy on required modules with Jasmine / Webpack?

Let's say I have a simple piece of code I want to test. This is much simpler than the code I'm actually working with, but should hopefully illustrate the problem better:

module.exports = foo;    

var someDependency = require('../someDependency.js');

function foo(someArgument) {
    var transformedArgument = someDependency(someArgument);
    useSomeInnerFunction(transformedArgument);
}

My function relies upon someDependency.js. I need to mock it in order to avoid testing it repeatedly through the functions that call it. What's the best way to do this?

  1. I could use some kind of dependency injection framework. Functions could take their dependencies as proper arguments and testing should be straightforward. But I'm not sure if there is a single popular solution for this - there don't seem to be any truly established libraries in this space. It feels like most people who write test-driven JavaScript are doing it in Angular, which provides a service-locator and magical dependency injection 'out of the box'. Adding a IOC container will also force me to rework my code which already heavily uses require calls.
  2. I could get Jasmine to spy on / mock the required functions. It's not clear how to do this - Jasmine is great for mocking methods on objects, but doesn't seem to provide any way to directly spy on a single function, which seems something of an oversight.

What is the best way for me to do this, from both a practical and a design perspective?

Aucun commentaire:

Enregistrer un commentaire