[英]undefined is not a function while testing ReactJS using Mocha
我正在嘗試使用ReactJs
和Mocha
測試具有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 && npm run test。 尋找解決方案並感謝您提供任何解決此問題的幫助,這非常令人沮喪。
如堆棧跟蹤所示, setup.js:5:35
(第5行,第35列)處的undefined is not a function
。
global.document = jsdom(markup || '')
global.window = document.createWindow() // <-- refers to this
通過執行global.document = ...
為節點的global
對象分配某些內容與在全局范圍內創建document
變量不同。 要訪問節點的全局對象上的某些內容,您將始終將其作為屬性訪問,因此請執行以下操作:
global.window = global.document.createWindow();
開關document.createWindow()
的document.defaultView
按照該文檔 ,它會工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.