corneyl
corneyl

Reputation: 598

`ReferenceError: Element is not defined` when running mocha tests on React+Onsenui app

While trying to setup a test environment I ran into the following problem. When I run the tests (using mocha ./src/test/.setup.js ./src/test/**.test.js), I get a Element is not defined error:

app\node_modules\onsenui\js\onsenui.js:603
  var originalCreateShadowRoot = Element.prototype.createShadowRoot;
                                 ^

ReferenceError: Element is not defined
    at app\node_modules\onsenui\js\onsenui.js:603:34
    at app\node_modules\onsenui\js\onsenui.js:359:7
    at Array.forEach (native)
    at initializeModules (app\node_modules\onsenui\js\onsenui.js:358:13)
    at app\node_modules\onsenui\js\onsenui.js:908:5
    (...)

How is this possible, isn't Element a basic DOM element?

The following versions are used:

The following .setup.js file is used:

require('babel-register')({
    presets: ["react","airbnb","es2015"]
});

var jsdom = require('jsdom').jsdom;

var exposedProperties = ['window', 'navigator', 'document'];

global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
    if (typeof global[property] === 'undefined') {
        exposedProperties.push(property);
        global[property] = document.defaultView[property];
    }
});

global.navigator = {
    userAgent: 'node.js'
};

documentRef = document;

And the test file is as follows:

import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';

import * as Ons from 'react-onsenui';
import MainPage from '../react/MainPage/MainPage.jsx';

describe("Component MainPage", function() {
    it("should have a Ons.Page component", function() {
        const wrapper = mount(<MainPage />);
        expect(wrapper.find(Ons.Page)).to.equal(true);
    });
});

Upvotes: 5

Views: 13180

Answers (1)

Norbert
Norbert

Reputation: 663

onsenui seems to be written for a browser enviroment, whilst you're executing it in a nodejs enviroment.

Element is a DOM api. nodejs has no DOM.

You could research using jsDom which is a node module that mimics the browser DOM for nodejs.

Edit: I think this package could solve your problems: https://github.com/rstacruz/jsdom-global I checked, it should place a 'Element' property in the global.

Upvotes: 5

Related Questions