Search code examples
node.jsunit-testingsequelize.js

Sequelize how to mock a model with jest?


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?


Solution

  • 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