Skip to content

Instantly share code, notes, and snippets.

@Hyllesen
Created December 11, 2019 06:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hyllesen/20c9e59d51d058e97bccd5e5fca587ac to your computer and use it in GitHub Desktop.
Save Hyllesen/20c9e59d51d058e97bccd5e5fca587ac to your computer and use it in GitHub Desktop.
//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);
}
};
@Harshverm776
Copy link

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() ???

@code0monkey1
Copy link

code0monkey1 commented Aug 31, 2022

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