We will begin development by first writing E2E tests. In the previous chapter, we already tested a scenario where the profile is not supplied. In these new E2E tests, we will add two more scenarios where the client provides a profile object—one using an invalid profile, the other a valid one.
Therefore, we must first decide what constitutes a valid profile; in other words, what should the structure of our profile object be? There are no right or wrong answers, but for this book, we will use the following structure:
{
"name": {
"first": <string>,
"last": <string>,
"middle": <string>
},
"summary": <string>,
"bio": <string>
}
All of the fields are optional, but if they are provided, they must be of the correct type.
Let's start with testing for the invalid profile scenario. In spec/cucumber/features/users/create/main.feature, add the following scenario outline:
Scenario Outline: Invalid Profile
When the client creates a POST request to /users/
And attaches <payload> as the payload
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 profile provided is invalid."
Examples:
| payload |
| {"email":"e@ma.il","password":"abc","profile":{"foo":"bar"}} |
| {"email":"e@ma.il","password":"abc","profile":{"name":{"first":"Jane","a":"b"}}} |
| {"email":"e@ma.il","password":"abc","profile":{"summary":0}} |
| {"email":"e@ma.il","password":"abc","profile":{"bio":0}} |
These examples cover the cases where properties have the incorrect type, and/or unsupported properties were provided.
When we run these tests, the And attaches <payload> as the payload shows up as undefined. This step definition should allow us to attach any arbitrary payload to the request. Try implementing this inside spec/cucumber/steps/index.js, and check your solution against the following one:
When(/^attaches (.+) as the payload$/, function (payload) {
this.requestPayload = JSON.parse(payload);
this.request
.send(payload)
.set('Content-Type', 'application/json');
});
Run the E2E tests again, and this time, the newly defined tests should fail. Red. Green. Refactor. We have now written a failing test; the next step is to implement the feature so that it passes the tests.