mardi 28 avril 2015

How can I mock RequireJs loader plugin responses in unit tests

The code I'm trying to test relies on RequireJs loader plugins. Example with requirejs/text:

require(['text!templates/foo'], function (data) {
  // handle loaded data
});

For a specific unit test, I'm trying to mock the response for text!templates/foo and override with one relevant for the test:

it('should load a template', function (done) {

  // TODO: mock 'text!templates/foo' here to return 'mock_data'

  // templateViewer uses the text plugin internally to do the actual loading
  templateViewer.templateFor('foo', function (error, templateData) {
    expect(templateData).toEqual('mock_data');
    done();
  });

});

I've looked at RequireJs dependency mock solutions, especially Squire.js but it seems they are all suited for mocking regular dependencies and not plugin responses.

I've also looked at stub libraries like sinon to maybe replace the actual require call but that seems problematic.

What's the recommended practice? I prefer not to replace the entire text plugin with a mock one in my requirejs configuration, just override some of its responses in specific tests.

My setup is node+mocha+requirejs

Aucun commentaire:

Enregistrer un commentaire