reactjs - Jest 如何测试反应表单提交?
问题描述
考虑以下组件:
import React, { Component } from "react";
import ImageUpload from "./ImageUpload/ImageUpload";
import axios from "axios";
class Dashboard extends Component {
state = {
fileName: ""
};
onFormSubmit = e => {
e.preventDefault();
const { group, country } = e.target;
axios.post("/api/dashboard", {
name: group.value,
country: country.value,
image: this.state.fileName
});
//TODO redirect the user
};
onFileNameChange = name => {
this.setState({ fileName: name });
};
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input type="text" name="group" placeholder="Group Name" />
<input type="text" name="country" placeholder="Country" />
<ImageUpload
fileName={this.state.fileName}
onFileNameChange={this.onFileNameChange}
/>
<button type="submit">Add Group</button>
</form>
</div>
);
}
}
export default Dashboard;
我试图伪造表单的提交并测试何时onFormSubmit
被调用。我做onFormSubmit
了一个间谍功能。但是,它根本没有被调用。
import React from "react";
import Dashboard from "components/admin/Dashboard/Dashboard";
import { shallow, render } from "enzyme";
describe("The Dashboard component", () => {
it("should not regress", () => {
const wrapper = render(<Dashboard />);
expect(wrapper).toMatchSnapshot();
});
it("should submit the form and send the group to server", () => {
const wrapper = shallow(<Dashboard />);
const preventDefault = jest.fn();
const event = {
preventDefault,
target: {
group: "Samrat",
country: "Nepal"
}
};
wrapper.instance().onFormSubmit = jest.fn();
wrapper.update();
wrapper.find("form").simulate("submit", event);
expect(wrapper.instance().onFormSubmit).toHaveBeenCalledWith(event);
});
});
解决方案
推荐阅读
- javascript - 如何限制使用 JavaScript 检查的复选框的数量(请不要使用 jquery)
- maven-plugin - 架构注册表构建失败,无法执行目标 org.apache.maven.plugins:maven-plugin-plugin
- flutter - 连接到 Firebase 的水平列表视图
- javascript - Window.open 按钮单击时的弹出窗口阻塞问题
- html - PhpStorm 或 SublimeText:搜索特定标签的表单类名 (CSS)
- reactjs - 如何在按钮单击时将文本框值传递给兄弟组件
- java - TCP/IP 客户端向服务器发送多条消息
- pyspark - 使用 pyspark 从文本文件中读取数据时出现“无效语法”错误
- c - 将空指针传递给 Fortran C 绑定
- javascript - 如何更快地显示 20000 行数据?