Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest mock window.scrollTo

My React component calls window.scrollTo and when I run my jest tests, they pass, but there is a console error:

 console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Not implemented: window.scrollTo
    at Object.<anonymous>.module.exports (/private/var/www/samplesite.com/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17)
    at Window.scrollTo (/private/var/www/samplesite.com/node_modules/jsdom/lib/jsdom/browser/Window.js:544:7)
    at scrollTo (/private/var/www/samplesite.com/back-end/utils/library.jsx:180:12)
    at commitHookEffectList (/private/var/www/samplesite.com/node_modules/react-dom/cjs/react-dom.development.js:17283:26)
    at commitPassiveHookEffects (/private/var/www/samplesite.com/node_modules/react-dom/cjs/react-dom.development.js:17307:3)
    at Object.invokeGuardedCallbackImpl (/private/var/www/samplesite.com/node_modules/react-dom/cjs/react-dom.development.js:74:10)
    at invokeGuardedCallback (/private/var/www/samplesite.com/node_modules/react-dom/cjs/react-dom.development.js:256:31)
    at commitPassiveEffects (/private/var/www/samplesite.com/node_modules/react-dom/cjs/react-dom.development.js:18774:9)
    at wrapped (/private/var/www/samplesite.com/node_modules/react-dom/node_modules/scheduler/cjs/scheduler-tracing.development.js:207:34)
    at flushPassiveEffects (/private/var/www/samplesite.com/node_modules/react-dom/cjs/react-dom.development.js:18822:5) undefined

I have tried mocking it in a few ways (both in the test itself and also in a jest setupFiles that gets called before each test) , but the console error will not go away:

Attempt 1:

let window = {};
window.scrollTo = jest.fn();

Attempt 2:

let scrollTo = jest.fn();
Object.defineProperty(window, "scrollTo", scrollTo);

Attempt 3:

delete global.window.scrollTo;
global.window.scrollTo = () => {};

Attempt 4:

global.window = {};
global.window.scrollTo = () => {};

How can i get rid of this console error? Thanks.

like image 265
Alan P. Avatar asked Oct 28 '19 03:10

Alan P.


1 Answers

For me, mock window.scrollTo in each test case. Or, put the mock code into a window.setup.js file and add the path of this file into jest setupFiles configuration, both of these two ways work fine.

For example,

index.spec.tsx:

import React, { Component } from 'react';

class SomeComponent extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    e.preventDefault();
    window.scrollTo(0, 0);
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click Me!</button>
      </div>
    );
  }
}

export default SomeComponent;

index.spec.tsx, mock window.scrollTo in each test case.

import React from 'react';
import { shallow } from 'enzyme';
import SomeComponent from './';

describe('SomeComponent', () => {
  test('should handle click', () => {
    const wrapper = shallow(<SomeComponent></SomeComponent>);
    const mEvent = { preventDefault: jest.fn() };
    window.scrollTo = jest.fn();
    wrapper.find('button').simulate('click', mEvent);
    expect(mEvent.preventDefault).toBeCalled();
    expect(window.scrollTo).toBeCalledWith(0, 0);
  });
});

jest.config.js:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'enzyme',
  // setupFiles: ['/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/58585527/window.setup.js'],
  setupFilesAfterEnv: ['jest-enzyme'],
  testEnvironmentOptions: {
    enzymeAdapter: 'react16'
  },
  coverageReporters: ['json', 'text', 'lcov', 'clover']
};

Unit test result:

 PASS  src/stackoverflow/58585527/index.spec.tsx (6.114s)
  SomeComponent
    ✓ should handle click (12ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        6.947s

Or, create a window.setup.js file and put the path of the file in jest setupFiles:

window.setup.js:

window.scrollTo = jest.fn();

jest.config.js:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'enzyme',
  setupFiles: ['/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/58585527/window.setup.js'],
  setupFilesAfterEnv: ['jest-enzyme'],
  testEnvironmentOptions: {
    enzymeAdapter: 'react16'
  },
  coverageReporters: ['json', 'text', 'lcov', 'clover']
};

Unit test result:

 PASS  src/stackoverflow/58585527/index.spec.tsx
  SomeComponent
    ✓ should handle click (12ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.33s, estimated 7s

Both of them work fine.

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58585527

like image 160
slideshowp2 Avatar answered Oct 26 '22 23:10

slideshowp2