测试 window.location.origin 个 polyfill

Testing window.location.origin polyfill

我想编写一个测试来证明 polyfill 有效。我正在使用 mochachaijsdomjsdomwindow.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');
    });
});

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