【发布时间】:2016-12-23 13:39:01
【问题描述】:
我想编写一个测试来证明 polyfill 有效。我正在使用mocha、chai 和jsdom。 jsdom 将 window.location.origin 公开为只读属性,因此我无法强制使用 polyfill(尝试设置 global.window.location.origin = null 时抛出 TypeError: Cannot set property origin of [object Object] which has only a getter;
填充:
export default function polyfills () {
if (typeof window === 'undefined') {
return;
}
// http://tosbourn.com/a-fix-for-window-location-origin-in-internet-explorer/
if (!window.location.origin) {
let loc = window.location,
port = loc.port ? `:${loc.port}` : '';
loc.origin = `${loc.protocol}//${loc.hostname}${port}`;
}
}
jsdom 设置:
import jsdom from 'jsdom';
global.document = jsdom.jsdom(
'<!doctype html><html><body></body></html>',
{
url: 'https://www.google.com/#q=testing+polyfills'
}
);
global.window = document.defaultView;
global.navigator = window.navigator;
测试:
import {expect} from 'chai';
import polyfills from '../path/to/polyfills';
describe('the polyfill function', function () {
before(() => {
delete global.window.location.origin;
// polyfills(); // test still passes when this is commented out
});
it('correctly exposes the window.location.origin property', () => {
expect(global.window.location.origin).to.equal('https://google.com');
});
});
【问题讨论】:
标签: javascript mocha.js chai jsdom polyfills