在 React+Onsenui 应用程序上运行摩卡测试时出现“ReferenceError:元素未定义”

cor*_*eyl 5 mocha.js reactjs enzyme onsen-ui2

在尝试设置测试环境时,我遇到了以下问题。当我运行测试(使用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
    (...)
Run Code Online (Sandbox Code Playgroud)

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

使用以下版本:

  • 酶@2.4.1
  • 摩卡@3.0.2
  • onsenui@2.0.0-rc.17
  • 反应@15.3.1
  • 反应-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;
Run Code Online (Sandbox Code Playgroud)

并且测试文件如下:

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);
    });
});
Run Code Online (Sandbox Code Playgroud)

Nor*_*ert 4

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

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

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

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

  • `jsdom-global`确实解决了这个错误,但是仍然存在其他错误,原来jsDOM对web组件的支持也很差。这个答案对我帮助最大,但我会尝试切换到 Karma 运行程序以防止其他错误。 (2认同)