我尝试使用触发功能的按钮测试组件,该功能从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();
});
});
如何测试此功能? 我尝试模拟历史对象,但遇到相同的错误。 谢谢。
答案 0 :(得分:1)
找到解决方案:
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,
});
});
});
答案 1 :(得分:0)
尝试使用:
collectCoin()