- Mastering React Test:Driven Development
- Daniel Irvine
- 273字
- 2021-06-24 14:45:08
Extracting out a field-finder function
Both of our tests include the following line, which reaches inside the form to pull out the firstName field:
const field = form('customer').elements.firstName;
This DOM manipulation is not related to what we're testing: while we care about the value of field, we are not interested in how the DOM API works.
We can improve the readability of our tests by keeping code within tests at a high level of abstraction, and extracting lower-level logic into helper methods. Since our tests are passing at the moment, now is a great opportunity to refactor.
Extract this field variable into a new function called firstNameField, as shown:
const firstNameField = () => form('customer').elements.firstName;
In the process of converting this variable into a function, we renamed it from field to firstNameField. A short, generic variable name such as field is fine inside the short scope of a single test. But once you pull the variable up into the describe scope, you need to be more specific in your naming.
The last test we wrote now simplifies to this:
it('includes the existing value for the first name', () => {
render(<CustomerForm firstName="Ashley" />);
expect(firstNameField().value).toEqual('Ashley');
});
Update the first test in the same way:
it('renders as a text box', () => {
render(<CustomerForm />);
expectToBeInputFieldOfTypeText(firstNameField());
});
It's worth pointing out here that, if we hadn't extracted the three expectations into this function, we could have called this new function three times, rather than calling it once and saving that value in a variable. I probably wouldn't do this in my production code, but it's fine in tests; readability is more important than minimizing computation:
expect(firstNameField()).not.toBeNull();
expect(firstNameField()).toEqual('INPUT');
expect(firstNameField()).toEqual('text');
- C語(yǔ)言程序設(shè)計(jì)教程
- Delphi程序設(shè)計(jì)基礎(chǔ):教程、實(shí)驗(yàn)、習(xí)題
- 新一代通用視頻編碼H.266/VVC:原理、標(biāo)準(zhǔn)與實(shí)現(xiàn)
- Mastering Selenium WebDriver
- VMware vSphere 6.7虛擬化架構(gòu)實(shí)戰(zhàn)指南
- Blockly創(chuàng)意趣味編程
- Implementing Cisco Networking Solutions
- 劍指MySQL:架構(gòu)、調(diào)優(yōu)與運(yùn)維
- Apache Kafka Quick Start Guide
- 運(yùn)用后端技術(shù)處理業(yè)務(wù)邏輯(藍(lán)橋杯軟件大賽培訓(xùn)教材-Java方向)
- Create React App 2 Quick Start Guide
- 愛上micro:bit
- Access 2010數(shù)據(jù)庫(kù)應(yīng)用技術(shù)實(shí)驗(yàn)指導(dǎo)與習(xí)題選解(第2版)
- IBM Cognos TM1 Developer's Certification guide
- Tableau Desktop可視化高級(jí)應(yīng)用