Skip to content

Instantly share code, notes, and snippets.

@mayank23
Last active October 25, 2024 13:57
Show Gist options
  • Save mayank23/7b994385eb030f1efb7075c4f1f6ac4c to your computer and use it in GitHub Desktop.
Save mayank23/7b994385eb030f1efb7075c4f1f6ac4c to your computer and use it in GitHub Desktop.

Revisions

  1. mayank23 revised this gist Apr 24, 2019. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    Jest Mock Any Property on Window Utility - with automatic cleanup.
  2. mayank23 revised this gist Apr 24, 2019. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions mock-window-property.js
    Original file line number Diff line number Diff line change
    @@ -7,9 +7,9 @@ export default const mockWindowProperty = (property, value) => {
    writable: true,
    value,
    });
    afterAll(() => {
    window[property] = originalProperty;
    });
    });
    afterAll(() => {
    window[property] = originalProperty;
    });
    };

  3. mayank23 revised this gist Apr 24, 2019. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions mock-window-property.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,3 @@
    Here's a utility function for mocking any window property with automatic cleanup:

    export default const mockWindowProperty = (property, value) => {
    const { [property]: originalProperty } = window;
    delete window[property];
  4. mayank23 created this gist Apr 24, 2019.
    17 changes: 17 additions & 0 deletions mock-window-property.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    Here's a utility function for mocking any window property with automatic cleanup:

    export default const mockWindowProperty = (property, value) => {
    const { [property]: originalProperty } = window;
    delete window[property];
    beforeAll(() => {
    Object.defineProperty(window, property, {
    configurable: true,
    writable: true,
    value,
    });
    afterAll(() => {
    window[property] = originalProperty;
    });
    });
    };

    13 changes: 13 additions & 0 deletions test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    import mockWindowProperty from './mock-window-property'

    describe('my test', () => {
    mockWindowProperty('localStorage', {
    setItem: jest.fn(),
    getItem: jest.fn(),
    removeItem: jest.fn(),
    });
    it('works as expected', () => {
    window.localStorage.setItem('abc');
    expect(window.localStorage.setItem).toHaveBeenCalledWith('abc');
    });
    });