- Mastering React Test:Driven Development
- Daniel Irvine
- 257字
- 2021-06-24 14:45:11
Selecting from a dropdown
The Git tag for this section is appointment-form.
Let's move on to creating our appointment form. This form is used to book an appointment for a customer. The first field is the service the customer requires: cut, color, blow-dry, and so on:
- Create a new file, test/AppointmentForm.test.js, with the following test and setup:
import React from 'react';
import { createContainer } from './domManipulators';
import { AppointmentForm } from '../src/AppointmentForm';
describe('AppointmentForm', () => {
let render, container;
beforeEach(() => {
({ render, container } = createContainer());
});
const form = id =>
container.querySelector(`form[id="${id}"]`);
it('renders a form', () => {
render(<AppointmentForm />);
expect(form('appointment')).not.toBeNull();
});
});
- Fix this test by implementing the production code in src/AppointmentForm.js, as shown:
import React from 'react';
export const AppointmentForm = () => <form id="appointment" />;
- Create a nested describe block for the service field. We do this right away because we know this form will have multiple fields:
describe('service field', () => {
});
- Add the following test in the describe block:
it('renders as a select box', () => {
render(<AppointmentForm />);
expect(form('appointment').elements.service)
.not.toBeNull();
expect(form('appointment').elements.service.tagName)
.toEqual('SELECT');
});
- To make this test pass, modify the AppointmentForm component as follows:
export const AppointmentForm = () => (
<form id="appointment">
<select name="service" />
</form>
);
- Run tests and ensure all are passing.
- Simplify the test code by extracting a function for retrieving the service field. The function is essentially the same as the field function from the CustomerForm tests, the only difference being the form that it accesses:
const field = name => form('appointment').elements[name];
it('renders as a select box') {
expect(field('service')).not.toBeNull();
expect(field('service').tagName).toEqual('SELECT');
});
推薦閱讀
- iOS Game Programming Cookbook
- Python科學計算(第2版)
- Python網絡爬蟲從入門到實踐(第2版)
- Java從入門到精通(第5版)
- 人臉識別原理及算法:動態人臉識別系統研究
- Learn WebAssembly
- Web Application Development with MEAN
- Elasticsearch Server(Third Edition)
- C語言課程設計
- Web Development with MongoDB and Node(Third Edition)
- Mastering Unity 2D Game Development(Second Edition)
- Extreme C
- Visual Studio 2015高級編程(第6版)
- 交互式程序設計(第2版)
- 超好玩的Scratch 3.5少兒編程