javascriptangularjsmocha.jsjsdombabel-register

Can not test something with mocha when I have angular (1.6) as a dependency


I want to test a ng-redux reducer which have angular (1.6) as dependency. When I run the tests (npm test) with mocha, I get:

/data/work/mocha-angularjs/node_modules/angular/angular.js:33343
})(window);
   ^

ReferenceError: window is not defined

I tried to add jsdom to provide a fake window. But it still fails during the import of angular with this error:

module.exports = angular;
                 ^

ReferenceError: angular is not defined

Is there a way to make angular work properly in mocha/babel world?

I made a small GitHub project available here which reproduce the problem.

Here is the content of the project :

Package.json

{
  "name": "mocha-angularjs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "angular": "^1.6.3"
  },
  "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-latest": "^6.24.0",
    "chai": "^3.5.0",
    "jsdom": "9.12.0",
    "jsdom-global": "2.1.1",
    "mocha": "^3.2.0"
  },
  "scripts": {
    "test": "NODE_ENV=test mocha src/index.test.js --compilers js:babel-register --require jsdom-global/register"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/jtassin/mocha-angularjs.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/jtassin/mocha-angularjs/issues"
  },
  "homepage": "https://github.com/jtassin/mocha-angularjs#readme"
}

.babelrc

{
  "plugins": [],
  "presets": [
    "latest",
  ]
}

The code to test

import angular from 'angular';

export default function getFive() {
  return 5;
}

The test

import expect from 'chai';
import getFive from './index';

describe('desc', () => {
  it('my test', () => {
    expect(getFive()).to.equal(5);
  });
});

Solution

  • In case of someone needs it one day :

    I used angularcontext to solve the problem.

    package.json

      "devDependencies": {
        "angularcontext": "0.0.23",
        [...]
      },
    

    In my test file

    /* eslint-env mocha */
    /* eslint-disable import/no-extraneous-dependencies */
    import angularcontext from 'angularcontext';
    
    before((done) => {
      const context = angularcontext.Context();
      context.runFile('./node_modules/angular/angular.js', (result, error) => {
        if (error) {
          /* eslint-disable no-console */
          console.error(error);
          done(error);
        } else {
          global.angular = context.getAngular();
          done();
        }
      });
    });
    
    /* eslint-disable import/prefer-default-export */
    export const angular = global.angular;
    

    The github project has been updated with it.