- Mastering React Test:Driven Development
- Daniel Irvine
- 226字
- 2021-06-24 14:45:08
Passing in an existing value
Since this form will be used when modifying existing customers as well as adding new ones, we must set the text field's initial value to the existing first name if set:
it('includes the existing value for the first name', () => {
render(<CustomerForm firstName="Ashley" />);
const field = form('customer').elements.firstName;
expect(field.value).toEqual('Ashley');
});
To make this test pass, change the component definition to the following. We use a prop to pass in the previous first name value:
export const CustomerForm = ({ firstName }) => (
<form id="customer">
<input
type="text"
name="firstName"
value={firstName}
/>
</form>
);
Running tests again, you'll see that the test passes, but with a warning:
PASS test/CustomerForm.test.js
● Console
console.error node_modules/prop-types/checkPropTypes.js:19
Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.
in input (created by CustomerForm)
in form (created by CustomerForm)
in CustomerForm
To get rid of the warning, add the word readOnly to the input tag. You might be thinking: surely, we don't want a read-only field? You're right, but we need a further test, for modifying the input value, before we can avoid using the readOnly keyword. We'll add that test a little further on.
Always consider React warnings to be a test failure. Don't proceed without first fixing the warning.
推薦閱讀
- Mastering JavaScript Functional Programming
- ThinkPHP 5實(shí)戰(zhàn)
- ASP.NET Core 5.0開發(fā)入門與實(shí)戰(zhàn)
- 數(shù)據(jù)結(jié)構(gòu)(Python語言描述)(第2版)
- ADI DSP應(yīng)用技術(shù)集錦
- Mastering JavaScript Design Patterns(Second Edition)
- Python函數(shù)式編程(第2版)
- C語言程序設(shè)計(jì)教程
- SQL Server 2014 Development Essentials
- Effective C++:改善程序與設(shè)計(jì)的55個(gè)具體做法(第三版)中文版(雙色)
- 信息學(xué)奧林匹克競(jìng)賽初賽精講精練
- 微信公眾平臺(tái)開發(fā)最佳實(shí)踐
- Cinder:Begin Creative Coding
- 編程風(fēng)格:程序設(shè)計(jì)與系統(tǒng)構(gòu)建的藝術(shù)(原書第2版)
- Learning Node.js for Mobile Application Development