0

I have a mongoose model, setup as per below,

// Model.TS

export interface LocationInterface extends mongoose.Document {
  name: string;
  description: string;
}

export const Location = mongoose.model<LocationInterface>(
  process.env.DB_CONTAINER || "Null",
  locationSchema
);

I then Mock it with,

https://jestjs.io/docs/en/mock-function-api

//tests.ts

Import Location from ‘./model’;

Location.create = jest.fn();

Then I want to confirm when it sends a json response its recieved ok.

 it("should return json body in response", () => {
    Location.create.  // => no mockReturnValue method is avaliable here??

I have tried the below but it does not work. How can I mock an ES6 module import using Jest?

jest.mock("./model", () => ({
  Location: jest.fn()
}));

I have tried to use export default Location, which also does not work.

I have tried the below, which also did not work.

jest.mock("../../../src/models/location.model", () => Location.create);

I tried the below from https://codewithhugo.com/jest-mock-spy-module-import/

import * as mockDB from "./model";

jest.mock('.model', () => ({
  get: jest.fn(),
  set: jest.fn()
}));


expect(mockDb.Location.create. // -> No Methods available
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Terry
  • 1,621
  • 4
  • 25
  • 45

1 Answers1

0

This blog article resolved all my issues.

https://dev.to/terabaud/testing-with-jest-and-typescript-the-tricky-parts-1gnc

import { mocked } from "ts-jest/utils";
import Location from "/model";

jest.mock("../../../src/models/location.model", () => {
  return jest.fn();
});

it("should recieve a code 201 and json response", async () => {
    // Mock Response
    mocked(Location.create).mockImplementation(
      (): Promise<any> => {
        return Promise.resolve(dummyRecord);
      }
    );
    const response = await DatabaseService.createRecord(dummyRecord, Location);
    expect(response).toStrictEqual({
      code: 201,
      data: dummyRecord
    })
  });
Terry
  • 1,621
  • 4
  • 25
  • 45