我已经使用sequelize-auto包创建了我的模型,并在控制器中使用它们
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
}我在我的一个控制器方法中调用了用户模型的findAll函数
我想使用Jest测试我的控制器方法,并模拟findAll函数以返回一个空对象。我已经在测试文件中导入了模型,并模拟了findAll函数,如下所示:
//inside test case
models.User.findAll = jest.fn().mockImplementation(() => {
return {}
});
const spy = jest.spyOn(models.User, "findAll")
await controllerMethod(req, res,next);我的问题是,当我运行测试用例时,它会在控制器内运行实际的findAll()函数,而不是模拟的findAll()
即findAll()返回实际数据,而不是{}
任何帮助都将不胜感激
提前感谢
发布于 2021-10-06 21:14:38
欢迎来到Stack Overflow。我认为你的代码的问题在于spyOn是如何工作的。请参阅文档here,特别是以下内容:
Note: By default, jest.spyOn also calls the spied method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use jest.spyOn(object, methodName).mockImplementation(() => customImplementation) or object[methodName] = jest.fn(() => customImplementation);这告诉您spyOn实际调用的是原始方法,而不是模拟实现。
我这样做的方式(假设您不需要断言findAll是如何调用的)是根本不使用spyOn,而是创建一个从initModels返回的虚拟models,其中包含您的虚拟findAll方法。类似于以下内容:
const mockModels = {
User: {
findAll: jest.fn(() => {})
}
};
// And then in your test - be careful as jest.mock is "hoisted" so you need to make sure mockModels has already been declared and assigned
test('blah', () => {
jest.mock("../models/init-models", () => ({
initModels: jest.fn(() => mockModels,
});
await controllerMethod(req, res, next) // ...etc发布于 2021-10-20 13:42:18
我设法解决了我的问题,直到我找到一个更好的解决方案。
我创建了一个单独的models.js文件,并通过它导出了我所有的模型。从models.js文件而不是const sequelize = require('../database/db'); var models = require("../models/init-models").initModels(sequelize);导入模型到我的控制器
models.js
const sequelize = require('../database/db');
var models = require("./init-models").initModels(sequelize);
module.exports.User= models.User;
module.exports.Instrument = models.Instrument;
module.exports.sequelize = sequelize; //exported this too since I have used sequelize.fn in some of my controllersuserController.js
//const sequelize = require('../database/db');
//var models = require("../models/init-models").initModels(sequelize);
//var User = models.User;
const {User,sequelize} = require('../service/models'); //imported models this way
const controllerMethod = async (req,res,next) => {
//calls await User.findAll() and returns the results
}userController.test.js
const {controllerMethod} = require('../../../controllers/user');
const {User,sequelize} = require('../../../service/models');
//inside test case
jest.spyOn(User, "findAll").mockImplementation(() => {return Promise.resolve([])});
await controllerMethod(req, res,next);通过这种方式,findAll模拟了我想要的方式,并返回预期的[]
https://stackoverflow.com/questions/69470459
复制相似问题