This is my first unit test and i am stuck to test mouse event. I have a div where on mouse down I fetch offsetX and offsetY and store that value in state.
<div
className={`outputCanvasHolder ${
this.props.output.selection === "CLICK"
? "showOutput"
: "hideOutput"
}`}
onMouseDown={e => {
this.handleMouseDown(e.nativeEvent)
}}
onMouseMove={e => {
this.handleMouseMove(e.nativeEvent)
}}
onMouseUp={e => {
this.handleMouseUp(e.nativeEvent)
}}
>My div</div>
handleMouseDown = primitive => {
this.setState(
{
dragStartX: primitive.offsetX,
dragStartY: primitive.offsetY
}
)
}
Now I want to test it using jest
it("mouse down event", () => {
props.output.selection = "CLICK"
const wrapper = shallow(<ReAlignedImageCanvas {...props} />)
const canvasDiv = wrapper.find(".showOutput")
console.log(canvasDiv.debug())
canvasDiv.simulate("mousedown", {
target: {
name: "dragStartX",
value: 100
}
})
expect(wrapper.find(".test"))
expect(wrapper.find(".test-100").length).to.equal(1)
})
But I am getting error TypeError: Cannot read property 'offsetX' of undefined. Can you please tell me how to test this event
Here asyn await is needed to make mouseDown event synchronus. Component should be mount. Event should be a mock function. Mouse event should be invoked to the element. Offset values should be mocked.
it("mouse down event", async () => {
const mockCallBack = jest.fn()
props.output.selection = "CLICK"
props.canvas.allPrimitives = true
const wrapper = mount(
<ReAlignedImageCanvas onMouseDown={mockCallBack} {...props} />
)
await wrapper.find(".showOutput").invoke("onMouseDown")(
{
nativeEvent: {
offsetX: 200,
offsetY: 180
}
},
9000
)
expect(wrapper.state("dragStartX")).toBe(200)
expect(wrapper.state("dragStartY")).toBe(180)
})