- Building Enterprise JavaScript Applications
- Daniel Li
- 341字
- 2021-07-23 16:31:20
Implementing step definitions
To test our API server, we would need to run the server itself and send HTTP requests to it. There are many ways to send requests in Node.js:
- Using the request method provided by Node's native http module.
- Using the new Fetch Web API syntax: fetch is an improvement on the traditional XMLHttpRequest used to make AJAX (Asynchronous JavaScript And XML) requests from the client. We can use polyfills, such as isomorphic-fetch (https://www.npmjs.com/package/isomorphic-fetch), which will allow us to use the same syntax on the server.
- Using a library, such as request (https://www.npmjs.com/package/request), superagent (npmjs.com/package/superagent), axios (npmjs.com/package/axios), and many more.
Using the native http module allows us to be as expressive as possible because it works at the lowest-level API layer; however, this also means the code is likely to be verbose. Using the Fetch API might provide a simpler syntax, but it will still have a lot of boilerplate code. For example, when we receive a response, we must explicitly tell our code how we want to parse it.
For our use cases, using a library is probably the most appropriate. Libraries are more opinionated but they also save you from writing the same lines repeatedly; for example, response payloads are parsed automatically in most libraries. Of all the available libraries, I've found that superagent is the most suitable for our tests because it allows you to compose a request by chaining multiple steps together. To demonstrate, the following is the example given in superagent's README.md file:
request
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
.set('X-API-Key', 'foobar')
.set('accept', 'json')
.end((err, res) => {
// Calling the end function will send the request
});
This allows us to initiate a request object at the beginning, and each step in our scenario can simply modify that object to collectively compose the final request that we send to our test API server. Without further ado, let's install superagent:
$ yarn add superagent --dev