Mocha + React:未定义导航器 [英] Mocha + React: navigator is not defined
问题描述
我正在尝试为React组件编写第一个测试,并不断出错:
I'm trying to write the first test for React components and keep getting error:
ReferenceError: navigator is not defined
我有组件,其中一个子组件使用 codemirror 来显示可编辑的文本区域.事实是,在Codemirror中可以检查导航器的类型.而且由于我不是在浏览器中运行此代码,而是在带有node.js的终端中运行它,因此未定义.
I have component and one of it's children use codemirror for displaying editable textareas. The thing is that in codemirror there is a check for type of navigator. And since I run this code not in browser, but in terminal with node.js it's not defined.
SO的某些人建议设置全局变量,但它对我不起作用.这是测试代码:
Some folks on SO advised to set global variable, but it didn't work for me. Here is code of the test:
global.navigator = {
userAgent: 'node.js'
};
import React from 'react'
import { shallow, render } from 'enzyme'
import { expect } from 'chai'
import { MessagesView } from '../../components/MessagesView'
describe('components', () => {
describe('Message views', () => {
it('render buttons', () => {
})
})
})
还有设置导航器变量的方法吗?或者,也许我可以使用mocha选项设置全局变量?
Is there still a way to set navigator variable? Or maybe I can set global variables with mocha options?
推荐答案
在这里看看 https://github.com/airbnb/enzyme/blob/master/docs/guides/jsdom.md
基本上,您需要配置jsdom才能为您创建窗口对象.
Basically you need to configure jsdom to create the window object for you.
var jsdom = require('jsdom').jsdom;
global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js'
};
这应该放在Mocha的安装文件中.
This should be placed in the setup file of Mocha.
这篇关于Mocha + React:未定义导航器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!