【问题标题】:How to test controller, which has associations with another modules service? Nest.js如何测试与其他模块服务有关联的控制器?巢穴
【发布时间】:2020-04-08 17:11:51
【问题描述】:

我应该如何测试具有身份验证服务和用户服务的控制器? 我正在尝试遵循书中的 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.service.ts

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

@Injectable()
export class AuthService {}

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

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

@Injectable()
export class UserService {}

我在这里尝试对身份验证控制器进行一些 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 () => {});
  });
});

【问题讨论】:

    标签: testing controller jestjs tdd nestjs


    【解决方案1】:

    而不是使用overrideProvider,您应该直接在提供程序数组中设置模拟,类似于以下内容:

    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 也应该这样做,这样您就可以创建真正的单元测试,只测试直接类而忽略其余部分。 This repository of mine 展示了许多使用 NestJS 的项目的不同测试示例。看看可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 2020-06-10
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      • 2020-08-17
      相关资源
      最近更新 更多