官术网_书友最值得收藏!

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');
主站蜘蛛池模板: 天峻县| 岳西县| 黄梅县| 安多县| 蕲春县| 康乐县| 金山区| 香格里拉县| 宜宾县| 四川省| 延边| 榆中县| 南澳县| 东源县| 沽源县| 兖州市| 勐海县| 汝城县| 新巴尔虎右旗| 镇康县| 百色市| 清涧县| 禹城市| 固安县| 洮南市| 通渭县| 博野县| 祁门县| 临湘市| 舞钢市| 三门县| 吴江市| 永丰县| 万安县| 同江市| 定远县| 奇台县| 德江县| 渝中区| 天门市| 临泉县|