- Mastering React Test:Driven Development
- Daniel Irvine
- 154字
- 2021-06-24 14:45:08
Labeling the field
Let's add a label to the field so the user knows what they are typing in:
const labelFor = formElement =>
container.querySelector(`label[for="${formElement}"]`);
it('renders a label for the first name field', () => {
render(<CustomerForm />);
expect(labelFor('firstName')).not.toBeNull();
expect(labelFor('firstName').textContent).toEqual('First name');
});
Make this pass by changing the JSX fragment to read as follows:
<form id="customer">
<label htmlFor="firstName">First name</label>
<input
type="text"
name="firstName"
value={firstName}
readOnly
/>
</form>
The JSX htmlFor attribute sets the HTML for attribute. for couldn't be used in JSX because it is a reserved JavaScript keyword. The attribute is used to signify that the label matches a form element with the given ID, in this case, firstName.
Now we need to ensure that our input has that same id, so that they match up. Add the following next test:
it('assigns an id that matches the label id to the first name field', () => {
render(<CustomerForm />);
expect(firstNameField().id).toEqual('firstName');
});
Making that pass is as simple as adding in the new attribute:
<form id="customer">
<label htmlFor="firstName">First name</label>
<input
type="text"
name="firstName"
id="firstName"
value={firstName}
readOnly
/>
</form>
推薦閱讀
- Redis Applied Design Patterns
- 算法基礎:打開程序設計之門
- Magento 2 Theme Design(Second Edition)
- Python零基礎快樂學習之旅(K12實戰訓練)
- MATLAB實用教程
- 深度強化學習算法與實踐:基于PyTorch的實現
- 表哥的Access入門:以Excel視角快速學習數據庫開發(第2版)
- Learning Vaadin 7(Second Edition)
- 運用后端技術處理業務邏輯(藍橋杯軟件大賽培訓教材-Java方向)
- Python語言實用教程
- Modern C++ Programming Cookbook
- C++ Application Development with Code:Blocks
- GitHub入門與實踐
- Hadoop 2.X HDFS源碼剖析
- HTML5+CSS3+JavaScript 從入門到項目實踐(超值版)