mardi 21 juin 2016

How to test an Angular utility Service with Mocha and NodeJS

I have a Angular Service (some utility funtions for array crunching. Not a web service, no http, minimal use of $window object ➝ no need for UI/e2etesting here).

I wonder, what the correct way is to test it with mocha? (For consistency I want to stick with Mocha, since we use it all over our backend).

I did find an akward way to get the library and its dependencies under test... but only in hacky ways:

  • By way of require() I only get the bare modul.exports array, so I have to hack my way to the service function itself [4] and fill it with mock data...
  • require('angular-mocks') is not working ➝ ReferenceError: window is not defined
  • I have to give clumsy full paths for everything, i.e. lz-String...
  • obviously, I am missing out on the dependency management of angular (i.e. or requireJS in general. As you'd usually use such service.

Can someone point me into the right direction?

The utility service under test:

'use strict';

module.exports = [
  '$window',
  'appData',
  'LZString',
  'utility',
  Service
];

function Service ($window, appData, LZString, utility) {

  var ...

  return {
    parseResults   : parseResults,
    reset          : reset
  };

  //////////

  function parseResults (result) {
    ...
  }
}

...and my hackily-working unit test approach with mocha...

'use strict';

// requiring all kinds of useful libs, not a problem...
var chai = require('chai');
var assert = require('assert');
var should = chai.should();
var sinon = require('sinon');

// angular-mocks module is existing, but disabled. Gets me a
// (window, window.angular);  — ReferenceError: window is not defined
//   require('angular-mocks');

// this loads the above array object (no requireJS elegange)
var parserService = require('../src/js/utility.service.js');
var LZString = require('../src/js/vendor/lz-string.js');

// the service instance to be tested
var testling;

var $window, appData, LZString, utility;

// build a fresh library before every test
beforeEach(function () {

  mockUtility = {  // works and does the job, below
    isMobile : sinon.stub()
  }

  testling = parserService[5](  // UGLY HACK
    null,        // $window
    {},          // appData,
    LZString,    // LZString,
    mockUtility
  );

});


// tests =========
it('test1', function () {

    // no tests yet, but I do get the output...
    testling.reset();

}); // test1

Aucun commentaire:

Enregistrer un commentaire