0

I have a function like so, and I just cannot wrap my head around how to mock this use case. I was given the function this way, so I'm not sure I can change it unless there's just a much better way.

Function to test - window is global, so no need to pass in

getWindowNamespace() {
    if (!window.namespace) {
        return false;
    }
    return window[window.namespace];
}

It's like the same window object is being used as two different types and it's really throwing me.

Testing logic I have so far (only relevant code so this wouldn't run as is, but I can provide more information as needed. Right now, I'm able to test the first negative case, but not the final return line.

const mockWindow = (namespace) => {
    global.window = Object.create(window);
    Object.defineProperty(window, 'window', {
        value: {
            namespace: namespace,
        },
        enumerable: true,
        configurable: true,
        writable: true,
    });
    window[namespace] = {};
    window[namespace].log = jest.fn();
}

Maybe I need to create the window as an array instead? Define value differently within defineProperty?

Thank you in advance for any help!

Sarah
  • 669
  • 2
  • 8
  • 21

1 Answers1

0

You may need to spyOn global.window.get and return a namespace and the data which window[window.namespace] will be returned

this will allow you to return and mock value for global.window


describe('test', () => {
    jest.spyOn(global, 'window', 'get').mockImplementation(() => ({
        namespace: 'test1',
        test1: 'value' // <<< this is the custom field value depend on whatever namespace is
    }))
    it('should return false', () => {
        expect(getWindowNamespace()).toBe('value');
    });
})