玩笑/反应模拟scrollBy和.getBoundingClientRect函数

时间:2019-04-23 17:41:17

标签: javascript reactjs mocking jestjs spy

我有一个功能handleClick,它对使用getBoundingClientRect获取其第一个参数的元素使用scrollBy。我正在尝试使用玩笑/酶对此进行测试。

class myClass extends Component  {
    ...
    ...
    handleClick () {
        document.getElementById('first-id').scrollBy(document.getElementById('second-id').getBoundingClientRect().width, 0);
    }

    render() {
        return (
            <button className="my-button" onClick={this.handleClick()}>scroll</button>
        );
    }
}

我的测试:

it('calls scrollBy with correct params', () => {
    const props = {};
    myClassWrapper = mount(<myClass {...props} />);
    const scrollBySpy = jest.fn();
    global.document.getElementById = jest.fn(() => ({ scrollBy: scrollBySpy }));

    myClassWrapper.find('my-button').simulate('click');
    // expect(scrollBySpy).toHaveBeenCalledWith()
});

我试图测试用正确的参数调用scrollBy,但是运行此测试时出现以下错误:

Error: Uncaught [TypeError: document.getElementById(...).getBoundingClientRect is not a function] 

很抱歉,如果以前已经回答过这个问题,但是我看不到任何能解决我的问题的答案。预先谢谢你。

1 个答案:

答案 0 :(得分:1)

scrollBy的第一个结果上调用

getElementById,在getBoundingClientRect的第二个结果上调用getElementById,因此您需要在您要在模拟中返回的对象。

这是一个让您入门的有效示例:

import * as React from 'react';
import { mount } from 'enzyme';

class MyClass extends React.Component {
  handleClick() {
    document.getElementById('first-id').scrollBy(document.getElementById('second-id').getBoundingClientRect().width, 0);
  }

  render() {
    return (
      <button className="my-button" onClick={this.handleClick}>scroll</button>
    );
  }
}

it('calls scrollBy with correct params', () => {
  const props = {};
  const myClassWrapper = mount(<MyClass {...props} />);
  const scrollBySpy = jest.fn();
  const getBoundingClientRectSpy = jest.fn(() => ({ width: 100 }));
  global.document.getElementById = jest.fn(() => ({
    scrollBy: scrollBySpy,
    getBoundingClientRect: getBoundingClientRectSpy  // <= add getBoundingClientRect
  }));

  myClassWrapper.find('.my-button').simulate('click');
  expect(scrollBySpy).toHaveBeenCalledWith(100, 0);  // Success!
});
相关问题