- Mastering React Test:Driven Development
- Daniel Irvine
- 305字
- 2021-06-24 14:45:09
Using state instead of props
It's finally time to introduce some state into our component. Add the following test, which what should happen when the text field value changes:
it('saves new first name when submitted', async () => {
expect.hasAssertions();
render(
<CustomerForm
firstName="Ashley"
onSubmit={({ firstName }) =>
expect(firstName).toEqual('Jamie')
}
/>
);
await ReactTestUtils.Simulate.change( firstNameField(), {
target: { value: 'Jamie' }
});
await ReactTestUtils.Simulate.submit(form('customer'));
});
The call to Simulate.change dispatches a React onChange event to the field. The event object sends the value of the text field to the event handler, which we'll use to set state.
In the browser, this event would be dispatched after every keystroke; however, in our test, we simulate just the final change event. That's enough because we'll write our event handler to always overwrite previous changes. In other words, only the last change matters.
Follow these steps to make this pass:
- Import useState into the module by modifying the existing React import:
import React, { useState } from 'react';
- Change the customer constant definition to be assigned via a call to useState. The default state is the original value of customer. Note the relationship between the two pieces of code. This is an example of how we can "upgrade" existing code from one level of complexity to another—in this case, from a constant definition to a state variable:
const [ customer, setCustomer ] = useState({ firstName });
- Create a new arrow function that will act as our event handler. This uses the form of setCustomer that takes a function. Using this form ensures that we correctly apply updates in the right order:
const handleChangeFirstName = ({ target }) =>
setCustomer(customer => ({
...customer,
firstName: target.value
}));
- In the returned JSX, modify the input element as shown. We replace the readOnly property with an onChange property, hooking it up to the handler we just created:
<input
type="text"
name="firstName"
id="firstName"
value={firstName}
onChange={handleChangeFirstName}
/>
推薦閱讀
- Reporting with Visual Studio and Crystal Reports
- 零基礎PHP學習筆記
- Android開發精要
- Python進階編程:編寫更高效、優雅的Python代碼
- INSTANT Weka How-to
- UI智能化與前端智能化:工程技術、實現方法與編程思想
- Python高級機器學習
- Java EE 7 Development with NetBeans 8
- Mastering Apache Spark 2.x(Second Edition)
- SQL 經典實例
- 好好學Java:從零基礎到項目實戰
- 平面設計經典案例教程:CorelDRAW X6
- RESTful Web Clients:基于超媒體的可復用客戶端
- Learning Nessus for Penetration Testing
- Docker:容器與容器云(第2版)