使用mocha和ES6 / babel测试react-bootstrap

时间:2016-04-19 18:52:11

标签: javascript reactjs mocha babeljs react-bootstrap

我正在尝试使用Mocha编写React和React-bootstrap组件的单元测试。

我的所有javascript都是用ES6编写的,我使用babel来转换为ES5。

我正在使用的文件如下。

运行npm install后,我运行npm test。这失败,输出如下:

$ npm test

> @ test /Users/tda0106/test/npm
> mocha --compilers jsx:babel-register simple-test.jsx



  A simple test
    1) "before all" hook: render and locate element


  0 passing (34ms)
  1 failing

  1) A simple test "before all" hook: render and locate element:
     AssertionError: expected null to exist
      at Context.<anonymous> (simple-test.jsx:21:9)



npm ERR! Test failed.  See above for more details.

TestUtils.renderIntoDocument因为我无法看到而无法返回null。 TestUtil docs表示在导入window之前必须定义documentReact,这是test-dom.jsx的要点。

我确定在React之前加载了test-dom.jsx,因为在我添加行设置global.navigator之前,React在其代码中深深地抛出了一个错误,试图访问该变量。

知道我需要做些什么来使这项工作?

的package.json

{
  "dependencies": {
    "react": "^15.0.1",
    "react-bootstrap": "^0.28.5",
    "react-dom": "^15.0.1"
  },
  "scripts": {
      "test": "mocha --compilers jsx:babel-register simple-test.jsx"
  },
  "devDependencies": {
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babelify": "^7.2.0",
    "chai": "^3.5.0",
    "jsdom": "^8.4.0",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^15.0.1"
  }
}

测试dom.jsx

// React needs the basic dom objects defined before it is imported.  
// And babel moves the imports before the rest of the code. 
// So the dom setup needs to be in its own file and imported.

import jsdom from 'jsdom';


const document = jsdom.jsdom("hello world");
const window = document.defaultView;

// A super simple DOM ready for React to render into
// Store this DOM and the window in global scope ready for React to access
global.document = document;

global.window = window;

global.navigator = {userAgent: 'None'};

export default { document: document, window: window };

简单test.jsx

import TestDom from './test-dom.jsx';

import { expect } from 'chai';

import React from 'react';
import { Panel } from 'react-bootstrap';

import TestUtils from 'react-addons-test-utils';


const Map = () => (
    <Panel>A map </Panel>
);

describe('A simple test', () => {
     before('render and locate element', () => {
       const renderedComponent = TestUtils.renderIntoDocument(
            <Map />
        );

        expect(renderedComponent).to.exist; // This fails
    });



    it('test something', () => {
        expect(1+1).is('true');
    });
});

.babelrc

{
    "presets": [
        "es2015",
        "react"
    ]
}

0 个答案:

没有答案