vendredi 2 mars 2018

TypeError: document.createElement is not a function- React, Mocha, JSDOM testing

I had previously written a testing script which very much similar to the below given script. It was running fine with following version of libraries

"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"

I modified the way to create DOM using jsdom so that, the script runs with following version of libaries.

"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"

However I am getting an error as given below:

 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)

Here is my app testing file

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;
  });
});

Here is my testing helper file

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};

I had already searched for solution but unable to find any breakthrough. Can anybody of you can tell me why TestUtils.renderIntoDocument is not able to create a simple div.

Note: I have purposely placed a div inside TestUtils.renderIntoDocument call so that the test always pass for debuging purpose.

Aucun commentaire:

Enregistrer un commentaire