How to delete window object for testing purpose?

Viewed 876
function isWindowAvailable() {
    return typeof window !== 'undefined';
}

jest test

it('should return false if window is not available', () => {
    const windowClone = Object.assign({}, window);
    // @ts-ignore
    window = undefined;
    expect(isWindowAvailable()).toBe(false);
    window = windowClone;
});

I want to test the function isWindowAvailable() using jest by deleting or somehow mocking window object to undefined. deleting delete window did not work. What is the correct way to achieve this?

1 Answers

The problem is that window object only exists on the browser.
What you can do, is to use a helper class and mock the window property as follow:

const sinon = require('sinon');
const expect = require('chai').expect;

describe('Window test', () => {


    class WindowHelper {
        get window() {
            return !window ? undefined : window;
        }
    }

    it('verify window does not exists', () => {
        let windowHelper = new WindowHelper;
        sinon.stub(windowHelper, "window").value(undefined)

        function isWindowAvailable(helper) {
            return helper.window !== undefined;
        }

        expect(isWindowAvailable(windowHelper)).to.be.false;
        expect(windowHelper.window).to.be.undefined;
    });
});

In case you want to use the isWindowAvailable function, you will need to pass the helper. It would be better if you only use the helper class every time you want work with the window object, this way you will get window when you are in the browser and undefined in other cases.
Hope this help.

Related