- Mastering React Test:Driven Development
- Daniel Irvine
- 259字
- 2021-06-24 14:45:10
Modifying handleChange to work with multiple fields
The Git tag for this section is handle-change.
After adding all three fields, you will have ended up with three very similar onChange event handlers:
const handleChangeFirstName = ({ target }) =>
setCustomer(customer => ({
...customer,
firstName: target.value
}));
const handleChangeLastName = ({ target }) =>
setCustomer(customer => ({
...customer,
lastName: target.value
}));
const handleChangePhoneNumber = ({ target }) =>
setCustomer(customer => ({
...customer,
phoneNumber: target.value
}));
You can simplify these down into one function, but you'll need to modify your tests first. The calls to ReactTestUtils.Simulate.change needs some extra data to be passed: the target's name. At runtime, this property is passed to all event handlers by React.
Add that in now, as shown:
const itSubmitsNewValue = (fieldName) =>
it('saves new value when submitted', async () => {
...
await ReactTestUtils.Simulate.change(field(fieldName), {
target: { value: 'newValue', name: fieldName }
});
...
});
Test data should always be as simple as possible, by only including what's relevant for the test to pass. We omitted the name property initially because we didn't need it to make our tests pass. Now, we have an opportunity to simplify our production code, so we can include it.
Since the name of our fields is the same as the name of our customer properties, we can now destructure the event to pull out the target name, merging our event handlers into one, as shown. This uses the computed property name feature of ES6:
const handleChange = ({ target }) =>
setCustomer(customer => ({
...customer,
[target.name]: target.value
}));
推薦閱讀
- jQuery Mobile Web Development Essentials(Third Edition)
- Monkey Game Development:Beginner's Guide
- FFmpeg入門詳解:音視頻流媒體播放器原理及應用
- Cassandra Data Modeling and Analysis
- 用Flutter極速構建原生應用
- Reactive Programming With Java 9
- Visual Basic程序設計上機實驗教程
- Spring Boot實戰
- Visual Studio Code 權威指南
- 小程序從0到1:微信全棧工程師一本通
- 數字媒體技術概論
- Python應用與實戰
- 分布式數據庫HBase案例教程
- Web前端開發技術實踐指導教程
- AI輔助編程Python實戰:基于GitHub Copilot和ChatGPT