- 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.
推薦閱讀
- Hyper-V 2016 Best Practices
- Drupal 8 Blueprints
- Power Up Your PowToon Studio Project
- Java應(yīng)用開發(fā)與實踐
- Python從菜鳥到高手(第2版)
- PostgreSQL技術(shù)內(nèi)幕:事務(wù)處理深度探索
- SQL Server 2012數(shù)據(jù)庫管理與開發(fā)項目教程
- Learning FuelPHP for Effective PHP Development
- C語言開發(fā)基礎(chǔ)教程(Dev-C++)(第2版)
- Learning Continuous Integration with TeamCity
- Moodle 3 Administration(Third Edition)
- HikariCP數(shù)據(jù)庫連接池實戰(zhàn)
- Distributed Computing with Python
- Python Business Intelligence Cookbook
- 零基礎(chǔ)學(xué)Java(升級版)