- Advanced Node.js Development
- Andrew Mead
- 245字
- 2021-08-27 19:06:07
Making a request to fetch the Todos from the database
To do that, we have to call Todo.find. Now, Todo.find is really similar to the MongoDB native find method we used. We can call it with no arguments to fetch everything in that collection. In this case, we'll be fetching all of the Todos. Next up, we can attach a then callback. We're going to get this function called with all todos, and we can make some assertions about that.
.end((err, res) => {
if(err) {
return done(err);
}
Todo.find().then((todos) => { })
In this case, we're going to assert that the Todo we created does exist. We'll get started by expecting todos.length to toBe equal to the number 1, because we've added one Todo item. We're going to make one more assertion. We're going to expect that that one and only item has a text property equal to using toBe, the text variable we have in server.test.js.
Todo.find().then((todos) => { expect(todos.length).toBe(1); expect(todos[0].text).toBe(text); })
If both of these pass, then we can be pretty sure that everything worked as expected. The status code is correct, the response is correct, and the database looks correct as well. Now it's time to call done, wrapping up the test case:
Todo.find().then((todos) => { expect(todos.length).toBe(1); expect(todos[0].text).toBe(text); done(); })
We're not done quite yet. If either of these fail, the test is still going to pass. What we have to do is tack on a catch call.