如何测试与另一个模块服务关联的控制器? Nest.js

How to test controller, which has associations with another modules service? Nest.js

我应该如何测试一个有授权服务和用户服务的控制器? 我正在尝试遵循书中的 TDD 方法,但它不再像那样工作了。

有什么解决办法吗?

这是我要测试的控制器:auth.controller.ts

import { Controller, Post } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UserService } from '../user/user.service';

@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly userService: UserService,
  ) {}
  @Post()
  async signup() {
    throw new Error('Not Implemented!');
  }

  @Post()
  async signin() {
    throw new Error('Not Implemented Error!');
  }
}

这是一个将由 auth 控制器用来处理操作的服务:auth.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AuthService {}

这是我需要使用的外部服务,以便查找和验证用户user.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class UserService {}

我在这里尝试为 auth controller 做一些 TDD 测试:auth.controller.spec.ts

import { Test } from '@nestjs/testing';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserService } from '../user/user.service';

describe('EntriesController', () => {
  let authController: AuthController;
  let authSrv: AuthService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [AuthController],
      providers: [AuthService, UserService],
    })
      .overrideProvider(AuthService)
      .useValue({ signup: () => null, signin: () => null })
      .compile();

    authController = await module.get<AuthController>(AuthController);
    authSrv = await module.get<AuthService>(AuthService);
  });

  describe('signup', () => {
    it('should add new user to the database', async () => {
      expect(await authController.signin()).toBe(true);
      console.log(authController);
    });
  });

  describe('signin', () => {
    it('should sign in user, if credentials valid', async () => {});
  });
});

而不是使用 overrideProvider 你应该直接在 providers 数组中使用类似这样的东西设置模拟:

beforeEach(async () => {
  const module = await Test.createTestingModule({
    controllers: [AuthController],
    providers: [
      {
        provide: AuthService,
        useValue: { signup: () => null, signin: () => null }
      },
      UserService
    ],
  })
  .compile();

  authController = await module.get<AuthController>(AuthController);
  authSrv = await module.get<AuthService>(AuthService);
});

UserService 也应该这样做,这样您就可以创建真正的单元测试,只测试直接的 class 并忽略其余部分。 This repository of mine 展示了很多使用 NestJS 的项目的不同测试示例。看看可能会有帮助。