Making assertions about the POST request
We'll start with the status. I'm going to expect that the status equals 200, which should be the case when we send across valid data. After this, we can go ahead and make an assertion about the body that comes back. We want to make sure the body is an object and that it has the text property equal to the one we specified previously. That's exactly what it should be doing when it sends the body back.
Over inside of server.test.js, we can get that done by creating a custom expect assertion. If you can recall, our custom expect calls do get passed in the response, and we can use that response inside of the function. We're going to expect that the response body has a text property and that the text property equals using toBe, the text string we have defined:
request(app) .post('/todos') .send({text}) .expect(200) .expect((res) => { expect(res.body.text).toBe(text); })
If that's the case, great; this will pass. If not, that's fine too. We're just going to throw an error and the test will fail. The next thing we need to do is call end to wrap things up, but we're not quite done yet. What we want to do is actually check what got stored in the MongoDB collection, and this is why we loaded in the model. Instead of passing done into end like we did previously, we're going to pass in a function. This function will get called with an error, if any, and the response:
request(app) .post('/todos') .send({text}) .expect(200) .expect((res) => { expect(res.body.text).toBe(text); }) .end((err, res) => { });
This callback function is going to allow us to do a few things. First up, let's handle any errors that might have occurred. This will be if the status wasn't 200, or if the body doesn't have a text property equal to the text property we sent in. All we have to do is check if an error exists. If an error does exist, all we're going to do is pass it into done. This is going to wrap up the test, printing the error to the screen, so the test will indeed fail. I'm also going to return this result.
.end((err, res) => { if(err) { return done(err); } });
Now, returning it doesn't do anything special. All it does is stop the function execution. Now, we're going to make a request to the database fetching all the Todos, verifying that our one Todo was indeed added.