4

在尝试设置测试环境时,我遇到了以下问题。当我运行测试(使用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元素吗?

使用以下版本:

  • 酶@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;

并且测试文件如下:

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

1 回答 1

3

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

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

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

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

于 2016-09-06T21:01:37.103 回答