javascript - 用纯 Jest 库(无酶)测试反应形式不起作用
问题描述
目前我正在测试一个只有玩笑的反应形式。我的意图是:
- 测试提交按钮是否被点击
- 测试使用表单输入数据调用提交按钮
import React, {useState} from 'react';
export const CustomerForm = () => {
const [form, setForm] = useState({
fname: "",
lname: ""
})
const handleChange = (e)=> {
// console.log(e);
setForm({...form, [e.target.name]: e.target.value });
}
const clickSubmit = (e) => {
e.preventDefault();
props.handleSubmit(form);
}
return(
<form id="customer" onSubmit={clickSubmit}>
<label htmlFor="firstName">First name</label>
<input type="text" name="firstName" value="firstName" id="firstName" onChange={handleChange} />
<label htmlFor="lastName">Last name</label>
<input type="text" name="lastName" value="lastName" id="lastName" onChange={handleChange} />
<input type="submit" value="Submit"/>
</form>
);
}
it('check for form is clicked', () => {
.......
});
it('form is submitted with entered data', () => {
......
});
我完全迷失了,因为这是最简单的场景,我几乎不知道如何测试这两个基本条件。请建议如何进行此测试,以便我学习。
解决方案
If you dont want to use Enzyme for the testing. a recommendation could be to render the component and then with querySelector seach for the specific element you want trigger the event. You need to import "react-dom" and "@testing-library/react";
example:
let container;
//With beforeEach will create a new div for each test in the file and adding it.
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
it("check for form is clicked", () => {
act(() => {
ReactDOM.render(<CustomerForm />, container);
});
//querySelector to find the specific DOM element to want to trigger the event.
const firstName = container.querySelector("#firstName");
const button = container.querySelector("button");
firstName.change();
button.click()
expect(firstName.value).toBe('')
});
Here the doc for more information:https://es.reactjs.org/docs/test-utils.html
Hope it helps you or least give you an a idea
推荐阅读
- android - 如何在 TextInputLayout 中为文本/标题/错误设置差异填充?
- c++ - TSubclassOf<> 不存储类类型
- python - 如何在python3中声明数组
- javascript - 尽管生产环境,IE11 中编译的 Vue 代码的控制台错误
- php - Laravel 路由组不会在 API 中返回数据
- svg - inkscape 扩展 - 隐蔽使用节点到路径节点
- c# - .NET Core 2.1 字符串。创建
- android - 在 travis(排毒)中测试 android.emu.release:-read-only 错误
- ios - 我可以在没有苹果开发者帐户的真实苹果设备上测试我的 Flutter 应用程序吗?如果可以,我该怎么做?
- c++ - C++ 数学特殊函数中的 std::complex<>:技术规范或提案