Jest.js Nest无法解析UserService(UserRepository,UserFactory,?)的依赖项

fnvucqvd  于 11个月前  发布在  Jest
关注(0)|答案(1)|浏览(114)

Nest.js正在使用jest编写测试代码。依赖注入不起作用。即使应用模块中包含的所有提供程序,它也不起作用。

const mockAuthService = {
  hashPassword: jest.fn(),
};

const mockUserFactory = {
  createUser: jest.fn(),
};

const MockUserRepository = {
  create: jest.fn(),
  save: jest.fn(),
  find: jest.fn(),
  findOne: jest.fn(),
};

describe('UserService', () => {
  let userService: UserService;
  let mockUserRepository: Repository<User>;
  let authService: AuthService;
  let userFactory: UserFactory;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        UserService,
        { provide: getRepositoryToken(User), useValue: MockUserRepository },
        { provide: UserFactory, useValue: mockUserFactory },
        { provide: AuthService, useValue: mockAuthService },
      ],
    }).compile();

    userService = module.get<UserService>(UserService);
    mockUserRepository = module.get<Repository<User>>(getRepositoryToken(User));
    authService = module.get<AuthService>(AuthService);
    userFactory = module.get<UserFactory>(UserFactory);
  });

  it('Success', async () => {
    // given
    const user = new SignUpRequestDto();
    user.email = '[email protected]';
    user.password = 'testpassword';
    mockUserFactory.createUser.mockReturnValue(new User(user.email, user.password));
    MockUserRepository.findOne.mockRejectedValue([]);
    mockAuthService.hashPassword.mockResolvedValue('hashPassword');
    MockUserRepository.save.mockReturnValue(new User(user.email, user.password));

    // When
    const result = await userService.create(user);

    // Then
    expect(result).toHaveProperty('email', user.email);
  });

字符串
您无法创建所有提供程序。问题是什么?我们如何解决此问题?
用户服务的配置如下。

export class UserService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
    private userFactory: UserFactory,
    private authService: AuthService,
  ) {}

aurhwmvo

aurhwmvo1#

这是一个循环依赖问题。通过forwardRef解决。

相关问题