Testing window.location.origin polyfill

1.2k views Asked by At

I'd like to write a test to prove a polyfill works. I'm using mocha, chai, and jsdom. jsdom exposes window.location.origin as a readonly property so I can't force the polyfill to be used (throws TypeError: Cannot set property origin of [object Object] which has only a getter when attempting to set global.window.location.origin = null;

polyfill:

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;

test:

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

There are 1 answers

0
bcr On BEST ANSWER

Using Object.defineProperty worked:

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