Home > Back-end >  Nestjs mock Sequelize for unit-test
Nestjs mock Sequelize for unit-test

Time:09-20

I'm building a CRUD API using Nest.js and codding a unit-test for the service, but when I mock the Sequelize model, this is the code for the test:

import { getModelToken } from "@nestjs/sequelize";
import { Test, TestingModule } from "@nestjs/testing";

import { VacanciesService } from "../../vacancies.service";
import { DepartmentsServices } from "../../../departments/departments.service";
import { Departments } from "../../../departments/model/departments.model";
import { Vacancies } from "../../model/vacancies.model";

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

  const mockSequelizeDepartments = {
    findByPk: jest.fn(),
  };

  const mockSequelizeVacancies = {
    findAll: jest.fn(),
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        VacanciesService,
        { provide: getModelToken(Vacancies), useValue: { mockSequelizeVacancies } },
        DepartmentsServices,
        { provide: getModelToken(Departments), useValue: { mockSequelizeDepartments } },
      ],
    }).compile();

    service = module.get<VacanciesService>(VacanciesService);
  });

  it("should be defined", () => {
    expect(service).toBeDefined();
  });

  describe("List vacancies", () => {
    it("should list all vacancies and return an empty array", async () => {
      const list = await service.list();

      expect(list).toHaveLength(0);
      expect(mockSequelizeVacancies.findAll).toHaveBeenCalledTimes(1);
    });
  });
});

But when i run the test, it show the following error:

TypeError: this.vacanciesModel.findAll is not a function

      57 |
      58 |   async list() {
    > 59 |     const list = await this.vacanciesModel.findAll();
         |                                            ^
      60 |
      61 |     if (!list) throw new NotFoundException("Nenhuma vaga encontrada");
      62 |

I've already tried to change the findAll to "findAll() { "Do something" }" or "findAll: () => { "Do something" }" and stilll the same error.

How can i fix this? Thanks for the help.

CodePudding user response:

Change your useValue from useValue: { mockSequelizeVacancies } to be useValue: mockSequelizeVacancies.

The first, you're making an object with the key mockSequelizeVacancies and value { findAll: jest.fn() }, the second you're just injecting the object { findAll: jest() }

  • Related