There will be two sides to this express route, the actual setup in server.js and the test. We can start inside server.js. In here, we'll make a new route. First, let's add a few comments to specify exactly what we'll do. It's going to be an HTTP GET route. The route itself will be /users and we can just assume this returns an array of users:
app.get('/', (req, res) => {
res.status(404).send({
error: 'Page not found.',
name: 'Todo App v1.0'
});
});
// GET /users
We can pass an array back through the send method, just like we do an object in the previous code. Now this array is going to be an array of objects where each object is a user. For now, we want to give users a name property and an age prop:
// GET /users
// Give users a name prop and age prop
Then we'll create two or three users for this example. Now once we have this done, we'll be responsible for writing a test that asserts it works as expected. That's going to happen in server.test.js. Inside server.test.js, we'll make a new test:
it('should return hello world response', (done) => {
request(app)
.get('/')
.expect(404)
.expect((res) => {
expect(res.body).toInclude({
error: 'Page not found.'
});
})
.end(done);
});
// Make a new test
And this test is going to assert a couple of things. First up, we assert that the status code that comes back is a 200 and we want to make an assertion that inside of that array and we'll do that using toInclude:
// Make a new test
// assert 200
// Assert that you exist in users array
Let's start with defining the endpoint first. Inside server.js, just following the comments, we'll call app.get so we can register the brand new HTTP endpoint for our application. This one is going to be at /users:
app.get('/users')
// GET /users
// Give users a name prop and age prop
Next up, we'll specify the callback that takes both request and response:
app.get('/users', (req, res) => {
});
// GET /users
// Give users a name prop and age prop
This will let us actually respond to the request, and the goal here is just to respond with an array. In this case, I'll call response.send passing in an array of objects:
app.get('/users', (req, res) => {
res.send([{
}])
});
The first object will be name. We'll set the name equal to Mike and we'll set his age equal to 27:
app.get('/users', (req, res) => {
res.send([{
name: 'Mike',
age: 27
}])
});
Then I can add another object. Let's add the second object to the array with a name equal to Andrew and an age equal to 25:
app.get('/users', (req, res) => {
res.send([{
name: 'Mike',
age: 27
}, {
name: 'Andrew',
age: 25
}])
});
In the last one, we'll set the name equal to Jen and the age equal to 26:
app.get('/users', (req, res) => {
res.send([{
name: 'Mike',
age: 27
}, {
name: 'Andrew',
age: 25
}, {
name: 'Jen',
age: 26
}])
});
Now that we have our endpoint done, we can save server.js, move into server.test.js, and start worrying about actually creating our test case.