Jest.js 提供程序的Nestjs单元测试问题

chhkpiq4  于 2023-05-21  发布在  Jest
关注(0)|答案(1)|浏览(193)

我是个测试新手
这是我的应用程序简化图

我想测试UserService
用户服务提供程序依赖于TypeOrmModule。
这里是userService.spec.ts

describe('test UserService', () => {
    let app: INestApplication;

    beforeAll(async () => {
        const moduleRef = await Test.createTestingModule({
            imports: [UserModule],
        }).compile()

        app = moduleRef.createNestApplication();
        await app.init();

    });
    afterAll(async () => {
        await app.close();
    });
});

但这给了我一个错误

Nest无法解析UserRepository(?)。请确保索引[0]处的参数DataSource在TypeOrmModule上下文中可用。

有什么问题吗?我该怎么解决?

n3h0vuf2

n3h0vuf21#

要隔离地测试服务,只需定义一个包含基本文件的TestingModule
例如,假设你有一个UserService,如下所示:

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import type { Repository } from 'typeorm';

import { User } from './user.entity';

export class UserService {
  constructor(@InjectRepository(User) private readonly userRepository: Repository<User>) {}

  async getOne(id: User['id']): Promise<User> {
    const user = await this.userRepository.findOne({ where: { id } });

    if (!user) {
      throw new NotFoundException(`User not found with id: ${id}`);
    }

    return user;
  }
}

然后编写一些单元测试来检查代码是否按预期工作:

import { NotFoundException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import type { Repository } from 'typeorm';

import { User } from './user.entity';
import { UserService } from './user.service';

describe('UserService', () => {
  let service: UserService;
  let mockedRepository: jest.Mocked<Repository<User>>

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [
        {
          // Register the test double (mock) of the TypeORM repository
          provide: getRepositoryToken(User),
          // Create a simple object with only the required methods
          useValue: {
            findOne: jest.fn()
          },
        },
        UserService,
      ],
    }).compile();

    service = module.get(UserService);
    mockedRepository = module.get(getRepositoryToken(User));
  });

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

  it('should get one user', async () => {
    // Arrange
    mockedRepository.findOne.mockResolvedValueOnce(new User());

    // Act
    const user = await service.getOne(1);

    // Assert
    expect(user).toBeDefined();
  });

  it('should fail if the user not exist', async () => {
    // Arrange
    mockedRepository.findOne.mockedResolvedValueOnce(null);

    // Act and Assert
    await expect(service.getOne(0)).rejects.toThrow(NotFoundException);
  });
});

正如您所看到的,单独测试组件比将模块作为一个整体进行测试更容易。

相关问题