mardi 1 mars 2016

stubbing a class in sinon that doesn't yet exist

Preamble: I've read lots of of SO and blog posts, but haven't seen anything that answers this particular question. Maybe I'm just looking for the wrong thing...

Suppose I'm writing sinon-based tests for a WidgetManager class that will operate on Widget objects. I have already written the class definition for WidgetManager, but haven't written anything for Widget yet. (Rationale: Widget itself might be really complex. But the tests for a WidgetManager should be decoupled from that complexity.)

What's best practices for testing WidgetManager code before I've defined the Widget class? I know that sinon mocks can only work on existing classes, and as far as I can tell, sinon stubs also need the class to exist before it can be stubbed.

To make it concrete, how would I test that Widget.create() is getting called exactly once with a single argument 'name' in the following code:

code under test

function WidgetManager() {
   this.widgets = []
}

WidgetManager.prototype.addWidget = function(name) {
    this.widgets.push(Widget.create(name));
}

testing code

var WidgetManager = require('../lib/widget-manager.js')
var sinon = require('sinon');

describe('WidgetManager', function() {
  describe('#addWidget', function() {
    it('should call Widget.create with the correct name', function() {
      var widget_manager = new WidgetManager();
      // what goes here?
    });
    it('should push one widget onto the widgets list', function() {
      var widget_manager = new WidgetManager();
      // what setup goes here?
      widget_manager.addWidget('fred');
      expect(widget_manager.widgets.length).to.equal(1);
  });
});

Aucun commentaire:

Enregistrer un commentaire