Mocking express and mongoose with jest in typescript Mocking express and mongoose with jest in typescript mongoose mongoose

Mocking express and mongoose with jest in typescript


To mock the Request and Response objects, you simply just pass them in with the values that you are using. In your case, this looks like this:

import { Request, Response, NextFunction } from 'express';import { Foo } from '../../src/models/Foo';import * as fooController from '../../src/controllers/foo';import { doesNotReject } from 'assert';describe('createFoo', async () => {  it('should add bars to the foo', async () => {    /**     * Spy on the model save function and return a completed promise.     * We are not testing the model here, only the controller so this is ok.     */    jest.spyOn(Foo.prototype, 'save').mockImplementationOnce(() => Promise.resolve());    /**     * Create a mock request and set type to any to tell typescript to ignore type checking     */    const mockRequest: any = {      user: {        _id: 1234,      },      body: {        bars: ['baz', 'qux', 'quux'],      },    };    /**     * Create a mock repsonse with only the methods that are called in the controller and     * record their output with jest.fn()     */    const mockResponse: any = {      status: jest.fn(),      json: jest.fn(),    };    /**     * Create a mock next function. It is okay to set its type to Express's NextFunction because     * we are mocking the entire function.     */    const mockNext: NextFunction = jest.fn();    await fooController.createFoo(mockRequest, mockResponse, mockNext);    expect(mockResponse.json).toHaveBeenCalledTimes(1);    expect(mockResponse.json).toHaveBeenCalledWith('bars');    expect(mockResponse.status).toHaveBeenCalledTimes(1);    expect(mockResponse.status).toHaveBeenCalledWith(200);  });});

I hope this helps!