使用Mocha测试ReactJS时,undefined不是函数

时间:2015-06-11 23:03:53

标签: javascript node.js reactjs mocha

我正在尝试使用ReactJsMocha测试包含2个输入字段的表单的简单页面。

当我运行测试时,我收到错误:

    TypeError: undefined is not a function
        at module.exports (/Users/johnp/Documents/myapp/work/projects/myapp-etd-portal/test/setup.js:5:35)
        at Object.<anonymous> (/Users/johnp/Documents/myapp/work/projects/myapp-etd-portal/test/component/NameTest.js:1:28)
        at Module._compile (module.js:460:26)
        at normalLoader (/Users/johnp/Documents/myapp/work/projects/myapp-etd-portal/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:160:5)
        at Object.require.extensions.(anonymous function) [as .js] (/Users/johnp/Documents/myapp/work/projects/myapp-etd-portal/node_modules/babel/node_modules/babel-core/lib/babel/api/register/node.js:173:7)
        at Module.load (module.js:355:32)
        at Function.Module._load (module.js:310:12)
        at Module.require (module.js:365:17)
        at require (module.js:384:17)
        at /Users/johnp/Documents/myapp/work/projects/myapp-etd-portal/node_modules/mocha/lib/mocha.js:192:27

以下是我的代码文件:

1.setup.js:基本设置文件

module.exports = function(markup) {
    if (typeof document !== 'undefined') return
    var jsdom          = require("jsdom").jsdom
    global.document    = jsdom(markup || '')
    global.window      = document.createWindow()

    var chai = require('chai');
    chai.config.includeStack = true;
    global.expect = chai.expect;
}

NameTest.js:实际测试页。

    NameTest.js
    require('../../test/setup')('<!doctype html><html><body></body></html>')
    var React          = require('react')
    var ReactAddons    = require('react/addons')
    var TestUtils = React.addons.TestUtils

describe('Name page component', function(){
    before('render element', function() {

        try {
            var renderedComponent = TestUtils.renderToString(
                <InputFieldItem />
            );
        } catch (e) {
            throw new Error(e);
        }
    });

    it('First & Last <input> fields should be of type "text"', function() {
        this.formElement = React.findDOMNode(TestUtils.findRenderedDOMComponentWithTag(renderedComponent, 'form'))
        this.firstNameElement = React.findDOMNode(TestUtils.scryRenderedDOMComponentsWithTag(renderedComponent, 'input')[0])
        this.lastNameElement = React.findDOMNode(TestUtils.scryRenderedDOMComponentsWithTag(renderedComponent, 'input')[1])

    });
});

我设置了gulp任务,并使用以下命令运行测试:gulp bundle&amp;&amp; npm运行测试。 寻找解决方案并感谢您解决此问题的任何帮助都非常令人沮丧。

2 个答案:

答案 0 :(得分:0)

堆栈跟踪显示undefined is not a function setup.js:5:35(第5行,第35列)。

global.document    = jsdom(markup || '')
global.window      = document.createWindow() // <-- refers to this

通过执行global为节点的global.document = ...对象分配内容,与在全局范围内创建document变量不同。要访问节点的全局对象上的某些内容,您将始终将其作为属性进行访问,因此请执行以下操作:

global.window = global.document.createWindow();

答案 1 :(得分:0)

根据docs切换document.createWindow() document.defaultView,这样就可以了。