BlinkUX / sequelize-mock

A simple mock interface specifically for testing code relying on Sequelize models
https://sequelize-mock.readthedocs.io
MIT License
139 stars 73 forks source link

Documentation example for mocking raw queries #53

Open justhamade opened 6 years ago

justhamade commented 6 years ago

Did see an example how to mock a raw query. I did see that you answered on #45 that it is possible. If I figure it out I will respond here with an example.

justhamade commented 6 years ago

I don't know if I did it the best way but it works. We are using jest.

In my example loadModels returns an object like

{
  sequelize: sequelize, // instance of sequelize connection
  models: [] // array of all the models that are imported
}
jest.mock('../models')

import Sequelize from 'sequelize'
import SequelizeMock from 'sequelize-mock'

import loadModels from '../models'
import handler from '../handler'
import {s3Upload} from '../utils/aws'
import {mockGetData} from '../models/mock-query'

const dbMock = new SequelizeMock()

export const mockGetData = [
  {
    name: 'Test Name',
    other: 'Test Other',
  },
]

describe('handler', () => {
  const mockExport = dbMock.define('myTableName', {
    name: 'test',
  })

  dbMock.close = () => Promise.resolve() // sequelize-mock does not include a close mock
  dbMock.QueryTypes = Sequelize.QueryTypes
  beforeEach(() => {
    dbMock.queryInterface.$clearHandlers()
    dbMock.queryInterface.$clearQueue()
    dbMock.models.export.$queryInterface.$clearHandlers()
    dbMock.models.export.$queryInterface.$clearQueue()

    loadModels.mockImplementation(() => ({
      Sequelize,
      sequelize: dbMock,
      export: mockExport,
    }))
  })

it('should do the query', async () => {
    dbMock.models.myTableName.$queryInterface.$useHandler((query) => {
      const testId = 'test-uuid'
      if (query === 'findOne') {
        return dbMock.models.export.build({
          id: testId,
          name: `test`,
        })
      }
      return Promise.resolve()
    })
    dbMock.$queueResult(mockGetData)
    await expect(handler({testId})).resolves.toMatchSnapshot()
  })
})