我之前编写过一个测试脚本,它与下面给出的脚本非常相似。使用以下版本的库
运行良好"chai": "^3.5.0",
"chai-jquery": "^2.0.0",
"jquery": "^2.2.1",
"jsdom": "^8.1.0",
"mocha": "^2.4.5",
"react-addons-test-utils": "^0.14.7"
我使用jsdom
修改了创建DOM的方法,这样脚本就可以运行以下版本的库。
"chai": "^4.1.2",
"chai-jquery": "^2.0.0",
"jquery": "^3.3.1",
"jsdom": "^11.6.2",
"mocha": "^5.0.1",
"react-addons-test-utils": "^15.6.2"
但是我收到如下错误:
App
1) "before each" hook for "renders something"
0 passing (31ms)
1 failing
1) App
"before each" hook for "renders something":
TypeError: document.createElement is not a function
at Object.renderIntoDocument (node_modules/react-dom/cjs/react-dom-test-utils.development.js:741:24)
at renderComponent (test/test_helper.js:21:40)
at Context.<anonymous> (test/components/app_test.js:8:17)
这是我的应用测试文件
import { renderComponent , expect } from '../test_helper';
import App from '../../src/components/App';
describe('App' , () => {
let component;
beforeEach(() => {
component = renderComponent(App);
});
it('renders something', () => {
expect(component).to.exist;
});
});
这是我的测试帮助文件
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-dom/test-utils';
import {JSDOM} from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = new JSDOM('<!doctype html><html><body></body></html>');
global.window = global.document.window;
console.log(global.document);
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<div></div>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
我已经搜索过解决方案但无法找到任何突破。你们中的任何人都可以告诉我为什么TestUtils.renderIntoDocument
无法创建一个简单的div。
注意:我故意将div
置于TestUtils.renderIntoDocument
内部,以便测试始终通过以进行调试。
答案 0 :(得分:1)
通过以下方式更改JSDOM的行:
global.dom = new JSDOM('<!doctype html><html><body></body></html>');
global.window = dom.window;
global.document = dom.window.document;
global.navigator = global.window.navigator;