Open justhamade opened 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()
})
})
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.