【发布时间】: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