Created
December 11, 2019 06:33
-
-
Save Hyllesen/20c9e59d51d058e97bccd5e5fca587ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Test file | |
const TodoController = require("../../controllers/todo.controller"); | |
const TodoModel = require("../../model/todo.model"); | |
const httpMocks = require("node-mocks-http"); | |
const newTodo = require("../mock-data/new-todo.json"); | |
// jest.mock("../../model/todo.model"); cant use this with the prototype.save | |
const saveMock = jest.fn(); | |
TodoModel.prototype.save = saveMock; | |
let req, res, next; | |
beforeEach(() => { | |
req = httpMocks.createRequest(); | |
res = httpMocks.createResponse(); | |
next = jest.fn(); | |
}); | |
describe("TodoController.SaveTodo", () => { | |
beforeEach(() => { | |
req.body = newTodo; | |
}); | |
it("should have a saveTodo function", () => { | |
expect(typeof TodoController.saveTodo).toBe("function"); | |
}); | |
it("should call TodoModel.save", () => { | |
TodoController.saveTodo(req, res, next); | |
expect(saveMock).toHaveBeenCalled(); | |
}); | |
}); | |
//Controller file | |
const TodoModel = require("../model/todo.model"); | |
exports.saveTodo = async (req, res, next) => { | |
try { | |
console.log(TodoModel); | |
const createdModel = await TodoModel.create(req.body); | |
console.log(createdModel); | |
createdModel.save(); | |
} catch (err) { | |
next(err); | |
} | |
}; |
This does not seem to work ! The save function gives an error while unit testing !
--------- This is the error message --------------
TodoController.SaveTodo › should call TodoModel.save
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
35 | it("should call TodoModel.save", () => {
36 | todoController.saveTodo(req, res, next);
> 37 | expect(saveMock).toHaveBeenCalled();
| ^
38 | });
39 | });
40 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
He @Hyllesen this code is not able to mock the save method. Your 3rd test case is failing.
I am trying to mock save from a long time.
Please can you provide some solution. It will be very helpful for me.
How to mock save() ???