mardi 27 octobre 2015

AngularJS directive unit test - ReferenceError: window is not defined

I'm attempting to run a simple unit test on an ES6 AngularJS directive using karma, mocha, and chai. My test fails with the following error:

VRS Home directive 1) "before each" hook for "should have h1 element" 0 passing (81ms) 1 failing 1) "before each" hook for "should have h1 element": ReferenceError: window is not defined at Object. (node_modules/angular/angular.js:28902:4) at Object.require.extensions.(anonymous function) [as .js] (node_modules/babel-core/lib/api/register/node.js:214:7) at Object. (node_modules/angular/index.js:1:63) at Object.require.extensions.(anonymous function) [as .js] (node_modules/babel-core/lib/api/register/node.js:214:7) at Object. (src/greeting.directive.js:9:16) at normalLoader (node_modules/babel-core/lib/api/register/node.js:199:5) at Object.require.extensions.(anonymous function) [as .js] (node_modules/babel-core/lib/api/register/node.js:216:7) at Context. (tests/unit/directive.unit.js:15:3)

Here is my directive:

import angular from 'angular';

function greeting() {
  return {
    restrict: 'E',
    scope: {
      name: '='
    },
    template: '<h1>Hello, {{name}}</h1>'
  };
}

export default angular.module('directives.greeting', [])
.directive('greeting', greeting)
.name;

Unit test:

let compile;
let scope;
let directiveElem;
const chai = require('chai');
const expect = chai.expect;

function getCompiledElement() {
  const element = angular.element('<greeting></greeting>');
  const compiledElement = compile(element)(scope);
  scope.$digest();
  return compiledElement;
}

beforeEach(() => {
  require('./../../src/greeting.directive');

  inject(($compile, $rootScope) => {
    compile = $compile;
    scope = $rootScope.$new();
  });

  directiveElem = getCompiledElement();
});

describe('VRS Home directive', () => {
  it('should have h1 element', () => {
    const h1Element = directiveElem.find('h1');
    expect(h1Element).toBeDefined();
    expect(h1Element.text()).toContain('Hello');
  });
});

Test script:

./node_modules/.bin/babel-node ./node_modules/.bin/_mocha ./tests/unit

Aucun commentaire:

Enregistrer un commentaire