- 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>
推薦閱讀
- Learning Single:page Web Application Development
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- Spring Cloud Alibaba核心技術與實戰案例
- Vue.js 3.x從入門到精通(視頻教學版)
- INSTANT Sencha Touch
- CKA/CKAD應試教程:從Docker到Kubernetes完全攻略
- PHP 7+MySQL 8動態網站開發從入門到精通(視頻教學版)
- Quantum Computing and Blockchain in Business
- Java EE企業級應用開發教程(Spring+Spring MVC+MyBatis)
- Oracle Data Guard 11gR2 Administration Beginner's Guide
- Spring Boot從入門到實戰
- Flutter從0基礎到App上線
- Learning RSLogix 5000 Programming
- Learning ClojureScript
- Spark內核設計的藝術:架構設計與實現