jeudi 31 mars 2016

Leaflet plugin not available in AngularJS controller during unit tests

I'm using Karma + Mocha to test a controller in Angular. The code below is a simplified example of the controller & test spec. L.Control.Locate is a LeafletJS plugin.

The problem

During a test run L.Control.Locate should exist when the controller is instantiated, but it doesn't. It throws: TypeError: L.Control.Locate is not a constructor.

The app works as expected in the browser.

The error occurs in both PhantomJS and Chrome.

In the test I've confirmed with a debugger that before MapCtrl2 is instantianted, L.Control.Locate is declared and attached to window.L.Control as it should be, but it's getting lost before the controller is instantiated.

The other standard properties for L are there as expected.

When I paste L.Control.Locate.js into the file before the controller declaration, the error disappears.

I've also tried injecting $window into the controller and looking at $window.L.Control.Locate, but it's still undefined.

Thanks for any clues.

Code:

angular.module('app')
.controller('MapCtrl2', function ($scope) {

  // Throws error here.
  var locateControl = new L.Control.Locate();

  // Do something with locateControl.

});

describe('MapCtrl2', function () {

  var controller, scope;
  beforeEach(module('app'));
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    controller = $controller('MapCtrl2', {
      $scope: scope
    });
  }));

  it('has L.Control.Locate', function() {
    expect(window.L.Control.Locate).to.be.an.instanceOf(Object)
  });

});

Aucun commentaire:

Enregistrer un commentaire