【问题标题】:simulate('scroll') on a div inside a React component returns `AssertionError: expected false to be true`在 React 组件内的 div 上模拟('scroll')返回 `AssertionError: expected false to be true`
【发布时间】:2017-01-18 02:20:51
【问题描述】:

我有一个 React 组件,我正在为其编写一些测试。我想测试一下,当组件中的div 滚动时,它会触发侦听该事件onScroll 的函数。不幸的是,Enzyme 的 simulate('click') 似乎没有像我预期的那样调用我的 spy 函数。

我的组件

import React from 'react';
import ReactDOM from 'react-dom';
import jQuery from 'jquery';
const $ = jQuery;

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.handleScroll = this.handleScroll.bind(this);
  }

  handleScroll(event) {
    return true;
  }

  render() {
    return(
      <div className="my-component" onScroll={this.handleScroll}>
        <h1>Hello world</h1>
      </div>
    );
  }
}

export default MyComponent;

我的测试

import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import { spy } from 'sinon';
import jsdom from 'jsdom';;

import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import MyComponent from '../views/components/my-component';

describe("<MyComponent />", () => {
  it('should trigger pagination when div.search-box scrolls', () => {
    const component = mount(<MyComponent />);
    const handleScrollSpy = spy(component.node, 'handleScroll');
    component
      .find('.my-component')
      .simulate('scroll')

    expect(handleScrollSpy.called).to.be.true;
  });
});

返回:AssertionError: expected false to be true

我尝试在测试中调用该函数,它导致 callCount 变为 1...

component.node.handleScroll();
console.log("Call count: ", handleScrollSpy.callCount);

这让我觉得我的测试问题与simulate 部分有关……

component
      .find('.search-box')
      .simulate('click')

请有人帮我确认一下我的处理方法是否正确,或者我确实做错了什么?

谢谢。


编辑

进一步阅读 Enzyme .simulate 文档发现以下内容:

即使名称暗示这模拟了实际事件, .simulate() 实际上将基于组件的 prop 事件你给它。例如, .simulate('click') 实际上会得到 onClick 属性并调用它。

我想知道是不是因为我没有将onScroll 作为道具传递,所以.simulate 目前没有触发handleScroll 函数。

【问题讨论】:

  • 我的假设是“滚动”事件没有被触发,因为你的div中没有任何东西可以滚动
  • @Torin 是的,好点。我也将其更改为onClick,但仍然没有通过。

标签: javascript reactjs mocha.js electron enzyme


【解决方案1】:

我不能说酶,但使用常规反应测试工具模拟你必须像这样传递一个 deltaY: TestUtils.Simulate.scroll(wrapper, { deltaY: 500 });

我想看看你是否可以将相同的 deltaY 传递给 .simulate 酶提供。

【讨论】:

    【解决方案2】:

    我没有使用 Sinon 进行间谍活动,但可能值得重写您的 handleScroll:

    handleScroll = (event) => {
      return true;
    }
    

    胖箭头会自动为你绑定'this',这意味着你可以在构造函数中删除this.handleScroll = ...。

    另一种选择是测试 handleScroll 函数的结果(这显然很棘手,因为它只返回 true)而不是测试它是否被调用。

    最后你可以测试组件渲染创建了一个 div 并将 onScroll 属性设置为this.handleScroll,然后单独测试handleScroll。

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      相关资源
      最近更新 更多