Home > Blockchain >  Is my Unit test for Nest.js project correct?
Is my Unit test for Nest.js project correct?

Time:09-16

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

I am very new to unit testing. Please take a moment to look at this. I'm really sorry if it's a weird question.

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');
      }
    });
  });
});

Please let me know if you further need any code or details. Looking forward to answers. Thank You.

CodePudding user response:

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);
});

  • Related