I have created my models using the sequelize-auto package and used them in my controllers
const sequelize = require('../database/db');
var models = require("../models/init-models").initModels(sequelize);
var User = models.User;
const controllerMethod = async (req,res,next) => {
//calls User.findAll() and returns the results
}
I have called the findAll function of User model in one of my controller methods
I want to test my controller method using Jest and want to mock the findAll function to return an empty object.
I have imported my models in the test file and mocked the findAll function as follows,
//inside test case
models.User.findAll = jest.fn().mockImplementation(() => {
return {}
});
const spy = jest.spyOn(models.User, "findAll")
await controllerMethod(req, res,next);
My question is when I run the test case it runs the actual findAll() function inside the controller instead of the mocked findAll()
i.e. findAll() returns actual data instead of {}
Any help would be greatly appreciated
Thanks in advance
Welcome to Stack Overflow. I think the issue with your code is some confusion on how
spyOnworks. Please see the documentation here specifically the following:What this is telling you is that
spyOnactual calls the original method, not the mock implementation.The way I would do this (and assuming you do not need to assert on how
findAllis called) is not usespyOnat all but create a dummymodelsthat is returned frominitModels, which has your dummyfindAllmethod on it. Something like the following: