【问题标题】:`ReferenceError: Element is not defined` when running mocha tests on React+Onsenui app`ReferenceError: Element is not defined` 在 React+Onsenui 应用程序上运行 mocha 测试时
【发布时间】:2016-09-06 20:43:22
【问题描述】:

在尝试设置测试环境时,我遇到了以下问题。当我运行测试时(使用mocha ./src/test/.setup.js ./src/test/**.test.js),我得到一个Element is not defined 错误:

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
    (...)

这怎么可能,Element不是基本的DOM元素吗?

使用以下版本:

  • enzyme@2.4.1
  • mocha@3.0.2
  • onsenui@2.0.0-rc.17
  • react@15.3.1
  • react-onsenui@0.7.5

使用以下 .setup.js 文件:

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;

而测试文件如下:

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

【问题讨论】:

    标签: reactjs mocha.js enzyme onsen-ui2


    【解决方案1】:

    onsenui 似乎是为浏览器环境编写的,而您在 nodejs 环境中执行它。

    Element 是一个 DOM api。 nodejs 没有 DOM。

    您可以使用 jsDom 进行研究,它是一个模仿 nodejs 的浏览器 DOM 的节点模块。

    编辑: 我认为这个包可以解决你的问题:https://github.com/rstacruz/jsdom-global 我检查了,它应该在全局中放置一个“元素”属性。

    【讨论】:

    • 我已经在使用 jsDOM,请参阅测试设置文件 .setup.js。可能jsDOM不支持Element api?
    • jsdom-global确实解决了这个错误,但是还有其他错误,原来jsDOM对webcomponents的支持也很差。这个答案对我帮助最大,但我会尝试切换到 Karma 跑步者以防止其他错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多