我想测试一个反应组件,其中onClick事件侦听器位于作为参数<Div>传递e.target给onClick函数的父元素上。我尝试使用enzyme.simulate并传递模拟函数和模拟参数来模拟点击,如下所示:let wrapper, cellClick, e;beforeEach(() => { cellClick = jest.fn(); e = { target: "div" }; wrapper = shallow(<Board onCellClick={cellClick} />);});afterEach(() => { cellClick.mockReset();});it("should call props.cellClick() whith e.target argument", () => { wrapper.simulate("click", e.target); expect(cellClick.mock.calls[0][0]).toBe(e.target);});这是反应组件:import React from "react";import PropTypes from "prop-types";import Div from "./styles";const Board = props => { return ( <Div onClick={e => props.onCellClick(e.target)}> <div id="board"> <div className="square" data-square="0" /> <div className="square" data-square="1" /> <div className="square" data-square="2" /> <div className="square" data-square="3" /> <div className="square" data-square="4" /> <div className="square" data-square="5" /> <div className="square" data-square="6" /> <div className="square" data-square="7" /> <div className="square" data-square="8" /> </div> </Div> );};Board.propTypes = { onCellClick: PropTypes.function};export default Board;这是测试结果: Interaction with the board cells › should call props.cellClick() whith e.target argument expect(received).toBe(expected) // Object.is equality Expected: "div" Received: undefined 49 | it("should call props.cellClick() whith e.target argument", () => { 50 | wrapper.simulate("click", e.target); > 51 | expect(cellClick.mock.calls[0][0]).toBe(e.target); | ^ 52 | }); 53 | }); 54 | at Object.toBe (components/Board/Board.test.js:51:40)我希望模拟方法模拟实际的点击,因此它有一个事件对象,然后它将包含子元素作为目标,而不需要我使用模拟对象。或者至少我想测试一个参数的存在而不检查它的值。
1 回答

MMTTMM
TA贡献1869条经验 获得超4个赞
看起来你正在传递e.target给wrapper.simulate...
...只需将其更改为e它应该可以工作:
it("should call props.cellClick() whith e.target argument", () => {
wrapper.simulate("click", e); // <= pass e
expect(cellClick.mock.calls[0][0]).toBe(e.target); // Success!
});
添加回答
举报
0/150
提交
取消