react onsenui mocha test error "Error: Invalid state"

react onsenui mocha test error "Error: Invalid state"

在我将 react-onsenui 从 0.7.3 更新到 1.0.0 之后。 我使用 mocha 来测试我的 webapp。错误发生如下:

Error: Invalid state
at /Users/*****/node_modules/onsenui/js/onsenui.js:581:11

onsenui.js'代码是这样的:

throw new Error('Invalid state');

您 运行 如何进行 Mocha 测试?我在 JSDOM 中使用 Mocha 时看到了这个错误。这只是发生的众多错误之一,因为 OnsenUI 需要一个真实的浏览器环境,而 JSDOM 不是。

我的方法是在我定义 DOM.

的 browser.js 文件中存根 OnsenUI 需要的所有内容

第581行调用的代码在window.getComputedStyle(document.documentElement, '')的结果中寻找键'transitionDuration',找不到就报错。我将其添加到我的 browser.js 文件中:

//** Polyfill for values missing from JSDOM
window.getComputedStyle = function(el1, el2) {
  return [
   "transitionDuration"
  ]
}

这解决了这个特定的错误,但还有更多错误。

继续阅读有关使用 OnsenUI 组件运行 进行 Mocha 测试的详细信息

JSDOM window 元素的属性不能用作 OnsenUI 的全局变量,所以我看到了很多错误,例如 Element is not definedNode is not defined 和很快。我通过将它们匹配到 window 属性(如果存在)或存根空函数来解决这些问题,如下所示:

// browser.js
global['Element'] = window.Element;
global['HTMLElement'] = window.HTMLElement;
global['WebComponents'] = function() {};
global['Node'] = window.Node;
global['Window'] = window;
global['Viewport'] = function() { return { setup: function() {} } }

这还不够运行宁。为了解决与 Web 组件和自定义元素相关的错误,我安装了 document-register-element,并将其导入到测试的顶部。我还需要从 https://github.com/megawac/MutationObserver.js 导入 MutationObserver,如下所示:

//shims.js
import './shims/mutationobserver';
global['MutationObserver'] = window.MutationObserver;

最后我的测试文件是这样的:

import 'babel-polyfill'
import React from 'react';
import { mount, shallow } from 'enzyme';
import {expect} from 'chai';
import document from './helpers/browser';
import './helpers/shims';
import 'document-register-element';

import Frame from '../react-app/components/frame';

describe('<Frame />', function () {
  it('renders without problems', function () {
    var wrapper = shallow(<Frame />);
    expect(wrapper.find('iframe')).to.have.length(1);
  }); 
});

这里是browser.js的全文:

 import { jsdom } from 'jsdom';

 //** Create a fake DOM to add the tests to
 const document = jsdom('<!doctype html><html><body></body></html>');
 const window = document.defaultView;

 //** Push the window object properties to the Mocha global object- no idea why it doesn't work for all of the properties
 Object.keys(window).forEach((key) => {
   if (!(key in global)) {
     global[key] = window[key];
   }
 });

 //** These ones need to be done manually
 global['Element'] = window.Element;
 global['HTMLElement'] = window.HTMLElement;
 global['WebComponents'] = function() {};
 global['Node'] = window.Node;
 global['Window'] = window;
 global['Viewport'] = function() { return { setup: function() {} } }

 //** Polyfill for values missing from JSDOM
 window.getComputedStyle = function(el1, el2) {
   return [
     "transitionDuration"
   ]
 }

 global.document = document;
 global.window = window;

有很多错误是因为没有真正的浏览器环境来执行这些库。 您可以使用 karma(一个测试 运行ner)来 运行 您的测试。并使用 chrome/Firefox/Phantomjs/Safari 或其他浏览器环境来测试您的代码。这些将解决您的问题。