Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

423
Vistas
Is my Unit test for Nest.js project correct?

I've written a unit test for my Nest.js project. I just want to confirm that is this test correct?

I am testing the nest service file. Below is the code:

tasks.service.ts

async getTaskById(id: string): Promise<Task> {
    const found = await this.taskModel.findById(id);

    if (!found) {
      throw new NotFoundException(`Task not found`);
    }

    return found;
 }

tasks.service.spec.ts

const mockTask = () => {
  return {
    _id: '613e4135ea46be481c2d88b2',
    name: 'Task 1',
    description: 'Go to school',
  };
};

const tasksServiceMock: Partial<TasksService> = {
  getTaskById: jest.fn().mockResolvedValue(mockTask()),
};

describe('TasksService', () => {
  let service: TasksService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        TasksService,
        {
          provide: TasksService,
          useValue: tasksServiceMock,
        },
      ],
    }).compile();

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

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

  describe('getTaskById', () => {
    it('should get task by ID', async () => {
      const task = await service.getTaskById(mockTask()._id);
      expect(task).toEqual(mockTask());
    });

    it('should throw task Not found error', async () => {
      tasksServiceMock.getTaskById = jest
        .fn()
        .mockRejectedValue(new NotFoundException('Task not found'));

      expect.assertions(2);

      try {
        await service.getTaskById('123456');
      } catch (e) {
        expect(e).toBeInstanceOf(NotFoundException);
        expect(e.message).toBe('Task not found');
      }
    });
  });
});

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are covering unit tests properly. I have 2 suggestions for syntax:

  1. You can define mockTask directly as an object instead of assigning the arrow function
  2. For the test case to verify error scenario you can use cleaner syntax (https://jestjs.io/docs/asynchronous#asyncawait) instead of try catch
it("should throw task Not found error", async () => {
  const mockError = new NotFoundException("Task not found");
  tasksServiceMock.getTaskById = jest.fn().mockRejectedValue(mockError);

  expect.assertions(2);

  await expect(service.getTaskById("123456")).rejects.toThrowError(mockError);
});

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda