开玩笑模拟window.scrollTo

时间:2019-10-28 03:38:33

标签: reactjs mocking jestjs jsdom

我的React组件调用window.scrollTo,当我运行笑话测试时,它们通过了,但是出现控制台错误:

 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

我尝试了几种模拟方式(在测试本身中以及在每次测试之前都被调用的笑话setupFiles中),但是控制台错误不会消失:

尝试1:

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

尝试2:

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

尝试3:

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

尝试4:

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

如何摆脱此控制台错误?谢谢。

2 个答案:

答案 0 :(得分:1)

对我来说,在每个测试用例中模拟window.scrollTo。或者,将模拟代码放入window.setup.js文件中,然后将此文件的路径添加到有趣的setupFiles配置中,这两种方式都可以正常工作。

例如,

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,在每个测试用例中模拟window.scrollTo

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']
};

单元测试结果:

 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

或者,创建一个window.setup.js文件,然后将文件的路径放入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']
};

单元测试结果:

 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

它们两个都工作正常。

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58585527

答案 1 :(得分:0)

设置     window.scrollTo = jest.fn(); 应该可以正常工作,如果您想为整个项目而不是每个测试文件分别定义它,可以在setupFilesAfterEnv

中定义它

或者在使用react-scripts时,您可以在./src/setupTests.js

中对其进行定义