- 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.
推薦閱讀
- Google Apps Script for Beginners
- 軟件架構設計:大型網站技術架構與業務架構融合之道
- Python從入門到精通(精粹版)
- Getting Started with PowerShell
- WebRTC技術詳解:從0到1構建多人視頻會議系統
- 軟件品質之完美管理:實戰經典
- Julia高性能科學計算(第2版)
- 動手學數據結構與算法
- R數據科學實戰:工具詳解與案例分析
- Java EE Web應用開發基礎
- 石墨烯改性塑料
- Building UIs with Wijmo
- Python Django Web從入門到項目實戰(視頻版)
- Mastering Data Analysis with R
- jMonkeyEngine 3.0 Beginner’s Guide