- Building Enterprise JavaScript Applications
- Daniel Li
- 374字
- 2021-07-23 16:31:26
Checking the payload property's format
Lastly, the email address field may be present and have the correct data type, but it may still not be a valid email. So, the final check is to ensure the email is a valid email address. You should get the drill by now: define a new feature inside spec/cucumber/features/users/create/main.feature, and check back here for the solution:
Scenario Outline: Request Payload with invalid email format
When the client creates a POST request to /users
And attaches a Create User payload where the email field is exactly <email>
And sends the request
Then our API should respond with a 400 HTTP status code
And the payload of the response should be a JSON object
And contains a message property which says "The email field must be a valid email."
Examples:
| email |
| a238juqy2 |
| a@1.2.3.4 |
| a,b,c@!! |
We are checking multiple examples here to give us confidence that our endpoint really won't accept an invalid email. In theory, the more examples we define, the better, because it gives us more confidence in our feature. However, E2E tests take a (relatively) long time to run; therefore, we must find a balance between confidence and speed. Here, we have specified three sufficiently diverse examples, which should cover most scenarios.
Next, let's define the step definition:
When(/^attaches an? (.+) payload where the ([a-zA-Z0-9, ]+) fields? (?:is|are) exactly (.+)$/, function (payloadType, fields, value) {
const payload = {
email: 'e@ma.il',
password: 'password',
};
const fieldsToModify = fields.split(',').map(s => s.trim()).filter(s => s !== '');
fieldsToModify.forEach((field) => {
payload[field] = value;
});
this.request
.send(JSON.stringify(payload))
.set('Content-Type', 'application/json');
});
Run the tests and see them fail. Then, implement the following application code to make them pass:
if (!/^[\w.+]+@\w+\.\w+$/.test(req.body.email)) {
res.status(400);
res.set('Content-Type', 'application/json');
res.json({ message: 'The email field must be a valid email.' });
return;
}
Run the tests again, make sure they all pass, and then commit your code:
$ git add -A && git commit -m "Check validity of email for Create User endpoint"