当我将角度(1.6)作为依赖时,无法用mocha测试某些东西

时间:2017-03-16 15:17:42

标签: javascript angularjs mocha jsdom babel-register

我想测试一个具有角度(1.6)作为依赖性的ng-redux减速器。 当我用mocha运行测试(npm测试)时,我得到:

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

ReferenceError: window is not defined

我试图添加jsdom以提供假窗口。但是在使用此错误导入角度时它仍然失败:

module.exports = angular;
                 ^

ReferenceError: angular is not defined

有没有办法在摩卡/巴贝尔世界中使角度正常工作?

我制作了一个小型github项目here,可以重现这个问题。

以下是该项目的内容:

的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",
  ]
}

要测试的代码

import angular from 'angular';

export default function getFive() {
  return 5;
}

测试

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

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

1 个答案:

答案 0 :(得分:0)

如果某人有一天需要它:

我使用angularcontext来解决问题。

的package.json

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

在我的测试文件中

/* 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;

github project已更新。