Cris
Cris

Reputation: 327

How to unit test a class function that makes a mongoose query?

I have a class with multiple class functions, one of which makes a mongoose query. Something like:

export class ExampleService {
  constructor(
    @InjectModel(Example.name) private exampleModel: Model<Example>,
    @InjectModel(MyMongoose.name) private myMongooseModel: Model <MyMongoose>
  ){}

  //function i want to unit test
  async addToCollection(name) {
    if(name.length < 1) throw new Error ('No name entered')
    else {
      this.myMongooseModel.query()
    }
  }

  //..some other functions that call addToCollection()

}

I would like to test that addToCollection() behaves as expected -- throws an error if name is not long enough, or that a query to myMongooseModel is made if the name is long enough.

I've tried mocking ExampleService, but that means I would also have to mock addToCollection and the query to myMongooseModel, which I don't think would be the right way of testing this function. How can I mock only the call to myMongooseModel?

Upvotes: 0

Views: 136

Answers (1)

hoangdv
hoangdv

Reputation: 16127

myMongooseModel is a dependency, just create a spy object and inject it to ExampleService.

Example:

describe("ExampleService", () => {
  let service: ExampleService;

  let exampleModelMock;
  let myMongooseModelMock;

  let logSpy;

  beforeEach(() => {
    logSpy = jest.spyOn(console, 'log'); // spy log function
    exampleModelMock = {}; // mock it
    myMongooseModelMock = {
      query: jest.fn(), // mock query function
    };

    service = new ExampleService(exampleModelMock, myMongooseModelMock); // inject dependencies
  });

  it("should NOT call query when name too short", async () => {
    await service.addToCollection("");

    expect(logSpy).toHaveBeenCalledWith('no name entered');
    expect(myMongooseModelMock.query).not.toHaveBeenCalled();
  });

  it("should call query when name is NOT too short", async () => {
    await service.addToCollection("long_name");

    expect(logSpy).not.toHaveBeenCalled();
    expect(myMongooseModelMock.query).toHaveBeenCalled();
  });
});

Upvotes: 1

Related Questions