3

I am trying to unit test a Mithril model using m.request in a DOM-less environment.

I have this test working as an integration test in a browser environment using the browser's XMLHttpRequest, but would like the option to run this in isolation.

I am considering mocking the response of XMLHttpRequest in order to get a properly initialized m.request, but I'm not sure where to start. I have a naive implementation of XMLHttpRequest driven out from the test and have looked into the source of m.request, but as a relative JS-newbie it's hard to follow.

Does it make more sense to stub out m.request entirely with to just test the transformation, since I trust that Mithril works (and is technically a dependency of the unit under test)? This scares me a bit as m.request has the chaining behavior which might be tricky to stub.

I would gladly accept an answer that generally describes the steps I would need to take to make some progress on this, and/or some advice on what makes sense to test.

require('chai').should();
require('mithril');

m.deps({ XMLHttpRequest: function() {
  this.open = function() {
  }

  this.setRequestHeader = function() {
  }

  this.send = function() {
  }
}});

var Curriculum = require('../../../app/modules/practice/practice.curriculum');

describe('Curriculum', function() {
  it('can retrieve a list of modules', function(done) {
    Curriculum.modules().then(function(modules) {
      modules.should.deep.equal([
        { name: 'Module 1' },
        { name: 'Module 2' },
        { name: 'Module 3' }
      ]);
      done();
    });
  });
});

Currently, running this test with mocha times out unhelpfully with no output or errors.

The source of the unit under test, if helpful:

module.exports = {
  modules: function() {
    // URL obscured to protect the innocent.
    return m.request({
      method: 'GET',
      url: 'http://working.url'
    }).then(function(objects) {
      var transformed = objects.map(function(object) {
        return { name: object.name };
      });
      return transformed;
    });
  }
};
jrh
  • 4,101
  • 2
  • 22
  • 27

1 Answers1

3

You can refer to Mithril's own test suite to see how it tests m.request itself

The mock object used in those tests can be found here

LeoHorie
  • 1,320
  • 11
  • 11