【问题标题】:Testing window.location.origin polyfill测试 window.location.origin polyfill
【发布时间】:2016-12-23 13:39:01
【问题描述】:

我想编写一个测试来证明 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');
    });
});

【问题讨论】:

    标签: javascript mocha.js chai jsdom polyfills


    【解决方案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');
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 2015-12-19
      • 2021-06-12
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多