Jest Mocking Default Instance

Example 1

const mockedPutObject = jest.fn();

jest.mock('@aws-sdk/client-s3', () => {
    return {
        S3: jest.fn(() => ({
            putObject: () => mockedPutObject()
        }))
    }
});

Example 2

jest.mock('uuid', () => ({ v4: () => '00000000-0000-0000-0000-000000000000' }));

Example 3

jest.mock('uuid');

const mockedUuidv4 = uuidv4 as jest.Mock;

mockedUuidv4.mockReturnValue('00000000-0000-0000-0000-000000000000');

Example 4

const mockedAjvValidate = jest.fn().mockReturnValue(true);

jest.mock('ajv', () => {
    return jest.fn(() => ({
        compile: () => () => mockedAjvValidate()
    }))
});

Example 5

jest.mock('moment', () => () => ({ format: () => '30-12-2021' }));

Example 6

import { v4 as uuid } from 'uuid';

export interface IEvent {
    id?: string;
    eventType: string;
    data: any;
}

export interface IEventRepository {
    getEvent(id: string): IEvent | undefined;
    setEvent(event: IEvent): IEvent;
}

const createEvent = (event: IEvent): IEvent => ({ id: uuid(), ...event });

export class EventRedisRepository implements IEventRepository {

    constructor(private events: Array<IEvent> = []) { }

    getEvent(id: string): IEvent | undefined {
        return this.events.find(item => item.id === id);
    }
    setEvent(event: IEvent): IEvent {

        const newEvent: IEvent = createEvent(event);

        this.events.push(newEvent);

        return newEvent;
    }
}

export class EventCosmosDbRepository implements IEventRepository {

    constructor(private events: Array<IEvent> = []) { }

    getEvent(id: string): IEvent | undefined {
        return this.events.find(item => item.id === id);
    }
    setEvent(event: IEvent): IEvent {

        const newEvent: IEvent = createEvent(event);

        this.events.push(newEvent);

        return newEvent;
    }
}

import { Persister } from '../src';
import { EventRedisRepository, EventCosmosDbRepository, IEventRepository, IEvent } from './sample';

const mockedRedisGetEvent = jest.fn();

const mockedRedisSetEvent = jest.fn();

const mockedCosmosdbGetEvent = jest.fn();

const mockedCosmosdbSetEvent = jest.fn();

jest.mock('./sample', () => {
    return {
        EventRedisRepository: jest.fn(() => ({
            getEvent: () => mockedRedisGetEvent(),
            setEvent: () => mockedRedisSetEvent(),
        })),
        EventCosmosDbRepository: jest.fn(() => ({
            getEvent: () => mockedCosmosdbGetEvent(),
            setEvent: () => mockedCosmosdbSetEvent(),
        })),
    }
});

const eventRedisRepository = new EventRedisRepository();

const eventCosmosdbRepository = new EventCosmosDbRepository();

const module_name = `${Persister.name}`;

describe(`${module_name} Test`, () => {
    it('should call setEvent function in both persisters', () => {

        const eventPersister = new Persister<IEventRepository>([eventRedisRepository, eventCosmosdbRepository]);

        const eventId = '4e0c71bb-eedf-43dd-b9a1-911a7ed6d74f';
        const newEvent: IEvent = { id: eventId, eventType: 'Submission', data: {} };

        eventPersister.set('setEvent', op => op(newEvent));

        expect(mockedRedisSetEvent).toHaveBeenCalledTimes(1);

        expect(mockedCosmosdbSetEvent).toHaveBeenCalledTimes(1);

    });
});

Example 6 – updated and short version

import { Persister } from '../src';
import { EventRedisRepository, EventCosmosDbRepository, IEventRepository, IEvent } from './sample';
import { mocked } from 'jest-mock'

jest.mock('./sample');

const eventRedisRepository = new EventRedisRepository();

const eventCosmosdbRepository = new EventCosmosDbRepository();

const mockedEventRedisRepository = mocked(eventRedisRepository, true);

const mockedEventCosmosdbRepository = mocked(eventRedisRepository, true);

const module_name = `${Persister.name}`;

describe(`${module_name} Test`, () => {
    it('should call setEvent function in both persisters', () => {

        const eventPersister = new Persister<IEventRepository>([eventRedisRepository, eventCosmosdbRepository]);

        const eventId = '4e0c71bb-eedf-43dd-b9a1-911a7ed6d74f';
        const newEvent: IEvent = { id: eventId, eventType: 'Submission', data: {} };

        eventPersister.set('setEvent', op => op(newEvent));

        expect(mockedEventRedisRepository.setEvent).toHaveBeenCalledTimes(1);

        expect(mockedEventCosmosdbRepository.setEvent).toHaveBeenCalledTimes(1);

    });
});

Leave a Reply

Your email address will not be published.