我对 Nest.js 项目的单元测试是否正确?

Is my Unit test for Nest.js project correct?

我已经为我的 Nest.js 项目编写了单元测试。我只是想确认这个测试是否正确?

我正在测试nest 服务文件。下面是代码:

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

您正确地涵盖了单元测试。 我有 2 个语法建议:

  1. 你可以直接将mockTask定义为一个对象而不是赋值箭头函数
  2. 对于验证错误场景的测试用例,您可以使用更简洁的语法 (https://jestjs.io/docs/asynchronous#asyncawait) 而不是 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);
});