Skip to content

Instantly share code, notes, and snippets.

@chengjianhua
Created March 29, 2017 09:11
Show Gist options
  • Save chengjianhua/bb2d25ab1733b8dce61d51d4ec9dc87b to your computer and use it in GitHub Desktop.
Save chengjianhua/bb2d25ab1733b8dce61d51d4ec9dc87b to your computer and use it in GitHub Desktop.
The setup for mocha test environment
import { jsdom } from 'jsdom';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
import { shallow, mount, render } from 'enzyme';
chai.use(chaiEnzyme());
global.should = chai.should();
global.shallow = shallow;
global.mount = mount;
global.render = render;
const exposedProperties = ['window', 'navigator', 'document'];
global.document = jsdom('');
global.window = document.defaultView;
/**
* this is a polyfill
* @see https://github.com/WickyNilliams/enquire.js/issues/91#issuecomment-47402945
*/
window.matchMedia || (
window.matchMedia = function(mediaQuery) {
return {
matches: false,
media: mediaQuery,
addListener: function() {},
removeListener: function() {}
};
});
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
exposedProperties.push(property);
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js'
};
global.documentRef = document;
@chengjianhua
Copy link
Author

用法有两种, 一种是在 npm 命令中 mocha test/.setup.js test/**/*test.js, 另一种是将其放在 test 目录的根目录下中添加一个文件 mocha.opts, 其中输入以下语句:

--require test/.setup.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment