- Building Enterprise JavaScript Applications
- Daniel Li
- 202字
- 2021-07-23 16:31:22
Asserting the correct response status code
Now that we understand how to use the debugger to examine the structure of complex objects, we are ready to implement the logic to check for the status of the response. To make our second test pass, we must send back a response with a 400 HTTP status code. With TDD, we should write the minimum amount of code that is required to make the test pass. Once the test passes, we can then spend some time refactoring the code to make it more elegant.
The most straightforward piece of logic to make the test pass is to simply check that the req object's method and url match exactly with 'POST' and '/users', and return with a 400 HTTP status code specifically for this scenario. If they do not match, send back the Hello World! response as before. After making the change, the requestHandler function should look something like this:
function requestHandler(req, res) {
if (req.method === 'POST' && req.url === '/users') {
res.statusCode = 400;
res.end();
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
}
Now, restart our API server and run the E2E tests; the first four steps should now pass.