mardi 23 février 2016

Cannot get angular directive to display template in test with typescript, karma and jasmine, what could be wrong?

I have a very simple directive like this:

class HelloDirective implements  ng.IDirective{
    public link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs:ng.IAttributes) => void;
    public template = '<div>Hello world</div>';
    public scope = {};

    construtor(){
    }

    public static Factory()
    {

       var directive = (/*list of dependencies*/) =>
       {
           return new HelloDirective(/*list of dependencies*/);
       };

       directive['$inject'] = ['/*list of dependencies*/'];
       return directive;
   }
}
export { HelloDirective};

This works fine when I use it in an app but when I try to use it in a test like this:

import  angular  = require('angular');
import ngMock = require('angular-mocks/ngMock');
import IAngularStatic = angular.IAngularStatic;
import {HelloDirective} from "../HelloDirective";

describe('helloDirective tests', () => {
   var $compile : ng.ICompileService;
   var $rootScope : ng.IRootScopeService;
   var app: ng.IModule;
   var helloElement: any;

   beforeEach(() => {
       app = angular.module('helloApp', [ngMock]);
       app.directive('hello', [HelloDirective.Factory()]);
       var elementHtml = '<hello/>';

       inject(function (_$compile_: any, _$rootScope_: any) {
           $rootScope = _$rootScope_;
           $compile = _$compile_;
       });

       helloElement = $compile(elementHtml)($rootScope);
       $rootScope.$digest();
   });

   it('should display helloDirective correctly', () => {
       expect(helloElement.text()).toBe('Hello world');
   });
});

I get: Expected '' to be 'Hello world'. If I use regular html e.g. Hello world instead of the test works fine and when I debug I see that the directives factory method is called.

What could be wrong?

Any help would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire