- Advanced Node.js Development
- Andrew Mead
- 278字
- 2021-08-27 19:06:08
Making assertions about the length of the Todos collection
Now, we can fetch from the database and make some assertions about the length of the Todos collection. I'm going to use Todo.find to fetch every single Todo inside of the collection. Then, I'll tack on a then callback, so I can do something with that data. In this case, I'll get the todos, and I'm going to assert something about its length. We're going to expect that todos.length equals toBe the number 0.
Todo.find().then((todos) => { expect(todos.length).toBe(0); });
There should be no Todos in the database before this test case runs, and since we're sending in bad data, this test case should not create any Todos. We can now call done and we can also tack on our catch callback, which we're going to need to do just like we did previously. We are going to call catch, taking that error argument and passing it into done:
Todo.find().then((todos) => { expect(todos.length).toBe(0); done(); }).catch((e) => done(e));
And now, we are done. I can save the file. This is going to restart nodemon, which is going to restart our test suite. What we should see is our two test cases, both of them passing. Over in the Terminal, we get just that. We have two test cases for POST /todos, and both are indeed passing:
It took a little while to set up the basic test suite in this section, but in the future as we add more routes, testing is going to be much easier. We're not going to have to set up the infrastructure; we're not going to need to create the test scripts or install new modules.