我更新react-onsenui从0.7.3到1.0.0之后。 我使用摩卡来测试我的web应用程序。发生这样的错误:反应onsenui摩卡测试错误“错误:无效状态”
Error: Invalid state
at /Users/*****/node_modules/onsenui/js/onsenui.js:581:11
onsenui.js'的代码是这样的:
throw new Error('Invalid state');
我更新react-onsenui从0.7.3到1.0.0之后。 我使用摩卡来测试我的web应用程序。发生这样的错误:反应onsenui摩卡测试错误“错误:无效状态”
Error: Invalid state
at /Users/*****/node_modules/onsenui/js/onsenui.js:581:11
onsenui.js'的代码是这样的:
throw new Error('Invalid state');
你是如何运行的摩卡测试?使用Mocha和JSDOM看到了这个错误。这只是因为OnsenUI期望一个真实的浏览器环境而发生的许多错误之一,并且JSDOM不是其中之一。
我的方法是将所有OnsenUI需要的东西存放在我定义我的DOM的browser.js文件中。
第581行调用的代码在window.getComputedStyle(document.documentElement, '')
的结果中查找关键字'transitionDuration',并在找不到它时发生错误。我添加了这个到我的browser.js文件:
//** Polyfill for values missing from JSDOM
window.getComputedStyle = function(el1, el2) {
return [
"transitionDuration"
]
}
这解决了这个特定的错误,但还有更多。
的JSDOM window
元素的属性是不可作为OnsenUI全局变量的血淋淋的细节,让我看到了很多错误,像Element is not defined
,Node is not defined
等等。我解决了这些由它们中匹配的窗口属性,如果它存在,或钳空函数,就像这样:
// 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(一个测试跑步者)来运行你的测试。并使用chrome/Firefox/Phantomjs/Safari或其他浏览器环境来测试您的代码。这些将解决您的问题。
有没有这方面的更新?目前它失败,因为缺少“MutationObserver”。 – pietro909