- Building Enterprise JavaScript Applications
- Daniel Li
- 357字
- 2021-07-23 16:31:27
Testing the success scenario
We have covered almost all of the edge cases. Now, we must implement the happy path scenario, where our endpoint is called as intended, and where we are actually creating the user and storing it in our database.
Let's carry on with the same process and start by defining a scenario:
Scenario: Minimal Valid User
When the client creates a POST request to /users
And attaches a valid Create User payload
And sends the request
Then our API should respond with a 201 HTTP status code
And the payload of the response should be a string
And the payload object should be added to the database, grouped under the "user" type
All steps are defined except the second, fifth, and last step. The second step can be implemented by using our getValidPayload method to get a valid payload, like so:
When(/^attaches a valid (.+) payload$/, function (payloadType) {
this.requestPayload = getValidPayload(payloadType);
this.request
.send(JSON.stringify(this.requestPayload))
.set('Content-Type', 'application/json');
});
The fifth step is a variation of the Then('the payload of the response should be a JSON object') step definition we have already defined, and therefore we can simply modify it to make it more generic:
Then(/^the payload of the response should be an? ([a-zA-Z0-9, ]+)$/, function (payloadType) {
const contentType = this.response.headers['Content-Type'] || this.response.headers['content-type'];
if (payloadType === 'JSON object') {
// Check Content-Type header
if (!contentType || !contentType.includes('application/json')) {
throw new Error('Response not of Content-Type application/json');
}
// Check it is valid JSON
try {
this.responsePayload = JSON.parse(this.response.text);
} catch (e) {
throw new Error('Response not a valid JSON object');
}
} else if (payloadType === 'string') {
// Check Content-Type header
if (!contentType || !contentType.includes('text/plain')) {
throw new Error('Response not of Content-Type text/plain');
}
// Check it is a string
this.responsePayload = this.response.text;
if (typeof this.responsePayload !== 'string') {
throw new Error('Response not a string');
}
}
});
For the last step, however, we actually need a database to write to. But we have already achieved a lot in this chapter. So let's review what we have done up to this point, and set up a database in the next chapter!