英文:
Sequelize how to mock a model with jest?
问题
我正在尝试为一个项目添加测试。
我有一个模型
UserModel.js
const { Model, DataTypes } = require('sequelize')
const sequelize = require('../../lib/db/config')
class User extends Model {}
User.init({
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
}
}, {
sequelize,
modelName: 'users'
});
然后,我想使用jest创建一个测试,对UserService
进行模拟,模拟UserModel
。
const User = require('src/Users/UserModel')
const UsersService = require('src/Users/UserService')
jest.mock('src/Users/UserModel');
describe('UsersService', () => {
it('Create User User', async () => {
User.create.mockResolvedValue({ id: 'mock-user-uuid' })
const mockUser = {
firstName: 'mock first',
lastName: 'mock last',
}
const result = await UsersService.createUser(mockUser)
expect(result).toEqual({ ...mockUser, id: 'mock-user-uuid' })
})
})
我收到以下错误
No Sequelize instance passed
User.init(
是否有一种方法可以绕过对init
的调用,或者创建模拟sequelize模型的适当方式是什么?
英文:
I am trying to add tests to a project.
I have a model
UserModel.js
const { Model, DataTypes } = require('sequelize')
const sequelize = require('../../lib/db/config')
class User extends Model {}
User.init({
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4
},
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING
}
}, {
sequelize,
modelName: 'users'
});
Then I want to create a test using jest for to UserService
mocking the UserModel
.
const User = require('src/Users/UserModel')
const UsersService = require('src/Users/UserService')
jest.mock('src/Users/UserModel');
describe('UsersService', () => {
it('Create User User', async () => {
User.create.mockResolvedValue({ id: 'mock-user-uuid' })
const mockUser = {
firstName: 'mock first',
lastName: 'mock last',
}
const result = await UsersService.createUser(mockUser)
expect(result).toEqual({ ...mockUser, id: 'mock-user-uuid' })
})
})
I get the following error
No Sequelize instance passed
User.init(
Is there a way to bypass the call to the init, or which should be the proper way to create a unit test mocking a sequelize model?
答案1
得分: 1
不要直接在您的服务文件中访问模型,而是创建数据访问层或存储库文件,这些文件将访问用户模型,在您的jest中,您可以模拟存储库文件函数。https://vin0d.medium.com/sequelize-mocking-with-jest-and-node-933c1f439579
英文:
Instead direct accessing models in your service file create data access layer or repository files which will access the user model and in your jest you can mock the repository file functions. https://vin0d.medium.com/sequelize-mocking-with-jest-and-node-933c1f439579
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论