测试window.location.origin polyfill

时间:2016-12-23 13:39:01

标签: javascript mocha chai jsdom polyfills

我想写一个测试来证明polyfill的工作原理。我正在使用mochachaijsdomjsdomwindow.location.origin公开为只读属性,因此我无法强制使用填充(尝试设置TypeError: Cannot set property origin of [object Object] which has only a getter时抛出global.window.location.origin = null;

填充工具:

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 setup:

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');
    });
});

1 个答案:

答案 0 :(得分:1)

使用Object.defineProperty工作:

describe('The polyfill function', function () {
    let loc;

    before(() => {
        loc = global.window.location;

        Object.defineProperty(loc, 'origin', {
            value: null,
            writable: true
        });

        polyfills();
    });

    it('correctly polyfills window.location.origin', () => {
        expect(loc.origin).to.equal('https://google.com');
    });
});