我有一个使用谷歌地图的反应模块,所以它要求谷歌在执行测试之前将javascript加载到DOM中。如何将这些外部库加载到jsdom中?
答案 0 :(得分:5)
您可以使用此助手类:
// File: loadDOM.js
const jsdom = require('jsdom');
export default (documentLoaded) => {
// Mock Image class since it's not found by default in jsdom
global.Image = class Image {
get complete() {
return true;
}
};
global.navigator = {
userAgent: 'node.js',
};
jsdom.env({
html: '<html><head></head><body></body></html>',
scripts: [
'https://maps.googleapis.com/maps/api/js?libraries=places',
'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js',
],
done: (err, win) => {
global.window = win;
global.document = win.document;
global.google = win.google;
global.$ = win.jQuery;
// Add other common globals
Object.keys(win).forEach((property) => {
if (typeof global[property] === 'undefined') {
global[property] = win[property];
}
});
// Done!
documentLoaded();
},
});
};
然后在测试中加载它:
import { expect } from 'chai';
import { beforeEach, describe, it } from 'mocha';
import React from 'react';
import { mount } from 'enzyme';
import Hello from '../../components/Hello';
// Load virtual DOM
import loadDOM from '../loadDOM';
describe('<Hello />', () => {
beforeEach((done) => {
loadDOM(done);
});
it('Renders Hello component', () => {
const props = {
title: 'World',
};
const wrapper = mount(<Hello {...props} />);
expect(wrapper.find('#title')).to.equal(props.title);
});
});