The first test we'll write is a test that verifies when we make an HTTP GET request to the / URL, we get Hello world! back. To do this, we will be calling it just like we did for our other tests in the previous chapter. We're still using mocha as the actual test framework. We're using SuperTest to fill in the gaps:
var app = require('./server').app;
it('should return hello world response')
Now we'll set up the function as follows:
it('should return hello world response', (done) => {
});
This is going to be an asynchronous call so I are providing done as the argument to let mocha know to wait before determining whether or not the test passed or failed. From here, we can now make our very first call to request. To use SuperTest, we call request passing in the actual Express application. In this case, we pass in the app variable:
it('should return hello world response', (done) => {
request(app)
});
Then we can start chaining together all the methods we need to make the request, make our assertions, and finally wrap things up. First up, you'll be using a method to actually make that request, whether it's a get, put, delete, or a post.
For now, we'll be making a get request, so we will use .get. The .get request takes the URL. So, we'll provide / (forward slash), just as we did in server.js:
it('should return hello world response', (done) => {
request(app)
.get('/')
});
Next up, we can make some assertions. To make assertions, we'll use .expect. Now .expect is one of those methods that does different things depending on what you pass to it. In our case, we'll be passing in a string. Let's pass in a string which will be the response body that we assert, Hello world!:
it('should return hello world response', (done) => {
request(app)
.get('/')
.expect('Hello world!')
});
Now that we're done and we've made our assertions, we can wrap things up. To wrap up a request in SuperTest, all we do is we call .end passing in done as the callback:
it('should return hello world response', (done) => {
request(app)
.get('/')
.expect('Hello world!')
.end(done);
});
This handles everything behind the scenes so you don't need to manually call done at a later point in time. All of it is handled by SuperTest. With these four lines (in the previous code), we have successfully tested our very first API request.