- 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');
});
推薦閱讀
- Web前端開發(fā)技術(shù):HTML、CSS、JavaScript(第3版)
- ThinkPHP 5實(shí)戰(zhàn)
- Visual Basic編程:從基礎(chǔ)到實(shí)踐(第2版)
- Mastering Selenium WebDriver
- Internet of Things with the Arduino Yún
- Linux命令行與shell腳本編程大全(第4版)
- Unity UI Cookbook
- 零基礎(chǔ)入門學(xué)習(xí)Python(第2版)
- Java面向?qū)ο蟪绦蛟O(shè)計(jì)
- 軟件測試綜合技術(shù)
- Java圖像處理:基于OpenCV與JVM
- 深入淺出Python數(shù)據(jù)分析
- Clojure High Performance Programming(Second Edition)
- Learning Cocos2d-JS Game Development
- Vue.js 3.x高效前端開發(fā)(視頻教學(xué)版)