I have a project connected to MongoDB. I am attempting to write a post method for adding a new book to the database. I’m using Jest, Mongoose, and Mockingoose.
In my get method, this line worked for simulating a failure to find a book by the id:
mockingoose(BooksModel).toReturn([], "find");
Now, I’m using create instead of find. Here is the code that will return a status 406 if creating a new book has failed:
req.body._id = new Types.ObjectId();
let bookAdded = await BooksModel.create(req.body);
if (!bookAdded) {
return res.status(406).send();
}
This is the test I have written to simulate a failure and return the 406 status:
test("BookPost return status code of 406 if creating new book failed", async () => {
let req = {
header: {},
body: {
title: "Lord of the Rings",
genre: "Fantasy",
author: "J.R.R. Tolkien",
read: true,
},
};
let res = makeMockRes();
mockingoose(BooksModel).toReturn(null, "create");
await func.inject({ BooksModel })(req, res);
console.log("Response status:", res.status.mock.calls[0][0]);
console.log("Response body:", res.json.mock.calls[0][0]);
expect(res.status).toHaveBeenCalledWith(406);
});
When I run the test, I get a status code 200, so the test fails.
I have ensured that the BooksModel path is correct, and that makeMockRes and mockingoose are required. Those are all at the top of the index.js.test page . I’ve added the console.logs in this test as you see, and when the test is ran they show that the status after the func.inject is 200, and the body is the book, including the _id. All of my other tests are working as they should.