- Building Enterprise JavaScript Applications
- Daniel Li
- 277字
- 2021-07-23 16:31:23
Asserting the correct response payload
The next test requires that the payload is a JSON object. Since our server is replying with a JSON object, the Content-Type header should also reflect this. Therefore, in our step definition, we should check for both of these criteria. In the spec/cucumber/steps/index.js, update the step definition to the following:
let payload;
...
Then('the payload of the response should be a JSON object', function () {
const response = result || error;
// Check Content-Type header
const contentType = response.headers['Content-Type'] || response.headers['content-type'];
if (!contentType || !contentType.includes('application/json')) {
throw new Error('Response not of Content-Type application/json');
}
// Check it is valid JSON
try {
payload = JSON.parse(response.text);
} catch (e) {
throw new Error('Response not a valid JSON object');
}
});
Now, restart our API server and we run the tests again; we should get a failing test:
$ yarn run test:e2e
....F-
...
Then our API should respond with a 400 HTTP status code
And the payload of the response should be a JSON object
Error: Response not of Content-Type application/json
at World.<anonymous> (spec/cucumber/steps/index.js:41:11)
- And contains a message property which says "Payload should not be empty"
Red. Green. Refactor. Now we have a failing test (red), the next step is to make it pass (green). To do this, we must set the Content-Type header to application/json and provide a JSON object in the payload. Change our requestHandler function to the following:
function requestHandler(req, res) {
if (req.method === 'POST' && req.url === '/users') {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({}));
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
}
Run the tests again, and the first five tests should have passed.