Skip to content

Instantly share code, notes, and snippets.

@llcoollasa
Created October 23, 2019 09:45
Show Gist options
  • Save llcoollasa/ab1442bac64ac8b53beda6ecdd32b386 to your computer and use it in GitHub Desktop.
Save llcoollasa/ab1442bac64ac8b53beda6ecdd32b386 to your computer and use it in GitHub Desktop.
Mongoose Mocking using Jest
jest.mock('mongoose');
import { model } from 'mongoose';
const calendarUserModelMock: any = {
find: jest.fn(() => calendarUserModelMock),
skip: jest.fn(() => calendarUserModelMock),
limit: jest.fn(() => calendarUserModelMock),
findByIdAndDelete: jest.fn(() => calendarUserModelMock),
};
const modelMock = model as jest.Mock;
modelMock.mockReturnValue(calendarUserModelMock);
import { calendarUserRepository } from './calendarUserRepository';
beforeEach(() => {
calendarUserModelMock.find.mockClear();
calendarUserModelMock.skip.mockClear();
calendarUserModelMock.limit.mockClear();
modelMock.mockClear();
});
test('it should retrieve calendarUserRepository document', async () => {
await calendarUserRepository.retrieve('someAccountId', 99, 199);
expect(calendarUserModelMock.find).toBeCalledTimes(1);
expect(calendarUserModelMock.skip).toBeCalledTimes(1);
expect(calendarUserModelMock.limit).toBeCalledTimes(1);
expect(calendarUserModelMock.find).toBeCalledWith({accountId: 'someAccountId'});
expect(calendarUserModelMock.skip).toBeCalledWith(99);
expect(calendarUserModelMock.limit).toBeCalledWith(199);
});
test('it should return empty array when there is no results in DB', async () => {
calendarUserModelMock.limit.mockResolvedValue([]);
const result = await calendarUserRepository.retrieve('someAccountId', 99, 199);
expect(result).toStrictEqual([]);
});
test('it should remove calendar user for the given id', async () => {
await calendarUserRepository.remove('someId');
expect(calendarUserModelMock.findByIdAndDelete).toBeCalledTimes(1);
expect(calendarUserModelMock.findByIdAndDelete).toBeCalledWith('someId');
});
declare module 'mongoose' {
interface Model<T extends Document, QueryHelpers = {}> {
replaceOne(conditions: any, replacement: any, options: ModelUpdateOptions,
callback?: (err: any, raw: any) => void): Query<any> & QueryHelpers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment