- Building Enterprise JavaScript Applications
- Daniel Li
- 334字
- 2021-07-23 16:31:26
Checking property type
Next, we must ensure that both our email and password fields are of type string and that the email address is formatted correctly. Have a go at defining a new scenario outline for this, and compare it to the following solution:
Scenario Outline: Request Payload with Properties of Unsupported Type
When the client creates a POST request to /users
And attaches a Create User payload where the <field> field is not a <type>
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 and password fields must be of type string"
Examples:
| field | type |
| email | string |
| password | string |
Again, run the tests and confirm that one of the steps is undefined. Then, try to implement the step definition yourself, and check back with the following solution:
When(/^attaches an? (.+) payload where the ([a-zA-Z0-9, ]+) fields? (?:is|are)(\s+not)? a ([a-zA-Z]+)$/, function (payloadType, fields, invert, type) {
const payload = {
email: 'e@ma.il',
password: 'password',
};
const typeKey = type.toLowerCase();
const invertKey = invert ? 'not' : 'is';
const sampleValues = {
string: {
is: 'string',
not: 10,
},
};
const fieldsToModify = fields.split(',').map(s => s.trim()).filter(s => s !== '');
fieldsToModify.forEach((field) => {
payload[field] = sampleValues[typeKey][invertKey];
});
this.request
.send(JSON.stringify(payload))
.set('Content-Type', 'application/json');
});
When we run the test, it fails because we have not implemented our application to handle that scenario. So, let's do that now by adding this if block to the end of the request handler for POST /users:
if (
typeof req.body.email !== 'string'
|| typeof req.body.password !== 'string'
) {
res.status(400);
res.set('Content-Type', 'application/json');
res.json({ message: 'The email and password fields must be of type string' });
return;
}
Now, run the tests to see them pass, and commit our changes to Git:
$ git add -A && git commit -m "Check data type of Create User endpoint payload"