我有一个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')
如果我正确地接近这个或者我确实做错了什么,有人可以向我确认吗?
感谢。
进一步阅读酶.simulate
文档揭示了以下内容:
即使名称暗示这模拟了一个实际的事件, .simulate()实际上将基于该目标来定位组件的prop 你给它的事件。例如,.simulate('click')实际上会得到 onClick道具并调用它。
我想知道是不是因为我没有通过onScroll
作为.simulate
目前没有触发handleScroll
功能的支柱。
答案 0 :(得分:1)
我没有使用Sinon进行间谍活动,但可能值得重写你的handleScroll
handleScroll = (event) => {
return true;
}
胖箭头会为你自动绑定'this',这意味着你可以删除构造函数中的this.handleScroll = ...
。
另一种选择是测试handleScroll
函数的结果(这显然很棘手,而它只返回true)而不是测试它被调用。
最后,您可以测试组件渲染创建了一个div,并将onScroll属性设置为this.handleScroll
,然后单独测试handleScroll
。
答案 1 :(得分:0)
我不能说酶,但使用常规反应测试工具模拟你必须传递deltaY像这样:
TestUtils.Simulate.scroll(wrapper, { deltaY: 500 });
我会看看你是否可以将相同的deltaY传递给.simulate酶提供的。