我应该如何测试一个有授权服务和用户服务的 Controller ? 我正在尝试遵循书中的 TDD 方法,但它不再像那样工作了。
有什么解决办法吗?
这是我要测试的 Controller :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 Controller 用来处理操作的服务: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
也应该这样做,这样您就可以创建真正的单元测试,只测试直接类而忽略其余类。 This repository of mine展示了许多使用 NestJS 的项目的不同测试示例。看一看可能会有所帮助。
关于testing - 如何测试与其他模块服务关联的 Controller ?嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59353236/