模拟点击事件和调用历史推送的测试函数(jest酶)



我尝试用一个触发函数的按钮来测试组件,该函数从useState获取一个状态,并导航到一个包含参数的新路径。如何测试该功能?我得到一个错误:

TypeError: history.push is not a function

组件:

import React, { useState, useEffect } from "react";
import "./Join.css";
import { useHistory } from "react-router-dom";
const Join = () => {
const history = new useHistory();
const [joinFormField, setJoinFormField] = useState({
username: "",
room: "JavaScript",
});
const changeFormHandler = (e) => {
setJoinFormField({
...joinFormField,
[e.target.name]: e.target.value,
});
};
const joinChatHandler = () => {
history.push("/chat", {
user: joinFormField,
});
};
return (
<div className="JoinContainer">
<header className="JoinHeader">
<h1>
<i className="fas fa-comments"></i> DeveloperChat
</h1>
</header>
<main className="JoinMain">
<form className="Form">
<div className="FormControl">
<label className="Label">NickName</label>
<input
className="Input"
type="text"
name="username"
id="username"
placeholder="Enter nickname..."
required
value={joinFormField.userName}
onChange={changeFormHandler}
/>
</div>
<div className="FormControl">
<label className="Label">Choose Room</label>
<select
className="RoomSelect"
name="room"
id="room"
value={joinFormField.room}
onChange={changeFormHandler}
>
<option value="JavaScript">JavaScript</option>
<option value="Python">Python</option>
<option value="PHP">PHP</option>
<option value="C#">C#</option>
<option value="Ruby">Ruby</option>
<option value="Java">Java</option>
</select>
</div>
<button className="JoinBtn" onClick={joinChatHandler}>
Join Chat
</button>
</form>
</main>
</div>
);
};
export default Join;

规范文件:

import * as React from "react";
import { shallow } from "enzyme";
import Join from "../../../containers/Join/Join";
describe("MyComponent", () => {
it("should navigate to chat when click on join btn", () => {
const joinChatHandler = jest.fn();
const wrapper = shallow(<Join onClick={joinChatHandler} />);
wrapper.find("button").simulate("click");
expect(joinChatHandler).toHaveBeenCalled();
});
});

如何测试此功能?我试图模拟一个历史对象,但我得到了同样的错误。谢谢

找到的解决方案:

const mockHistoryPush = jest.fn();
jest.mock("react-router-dom", () => ({
...jest.requireActual("react-router-dom"),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
describe("click handler", () => {
it("should navigate to chat when click on join btn", () => {
const joinFormField = {
username: "",
room: "JavaScript",
};
wrapper.find("button").simulate("click");
expect(mockHistoryPush).toHaveBeenCalledWith("/chat", {
user: joinFormField,
});
});
});

尝试使用:

this.props.history.push(""/chat")

最新更新