Javascript e2e如何与guard nestjs配合
我想用nestjs创建一个名为Javascript e2e如何与guard nestjs配合,javascript,node.js,typescript,jestjs,nestjs,Javascript,Node.js,Typescript,Jestjs,Nestjs,我想用nestjs创建一个名为/users的端点,但我遇到了一个错误。我怀疑如何让一名后卫通过考试 第一个错误 Nest无法解析UserModel(?)的依赖项。请确保 索引[0]处的参数DatabaseConnection在 MongooseModule上下文 第二个错误 预计200个“正常”,401个“未经授权” 应用程序模块 @Module({ imports: [ MongooseModule.forRootAsync({ imports: [ConfigModu
/users
的端点,但我遇到了一个错误。我怀疑如何让一名后卫通过考试
第一个错误
Nest无法解析UserModel(?)的依赖项。请确保
索引[0]处的参数DatabaseConnection在
MongooseModule上下文
第二个错误
预计200个“正常”,401个“未经授权”
应用程序模块
@Module({
imports: [
MongooseModule.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
uri: configService.mongoUri,
useNewUrlParser: true,
}),
inject: [ConfigService],
}),
GlobalModule,
UsersModule,
AuthModule,
PetsModule,
RestaurantsModule,
ConfigModule,
],
controllers: [],
providers: [],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(TokenDataMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
用户服务
@Injectable()
export class UsersService {
constructor(
@InjectModel('User') private readonly userModel: Model<UserDocument>,
private readonly utilsService: UtilsService,
private readonly configService: ConfigService,
) { }
async getAllUsers(): Promise<UserDocument[]> {
const users = this.userModel.find().lean().exec();
return users;
}
}
e2e文件
describe('UsersController (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
const testAppModule: TestingModule = await Test.createTestingModule({
imports: [AppModule, GlobalModule,
UsersModule,
AuthModule,
PetsModule,
RestaurantsModule,
ConfigModule],
providers: [],
}).compile();
app = testAppModule.createNestApplication();
await app.init();
});
it('GET all users from API', async () => {
// just mocked users;
const users = getAllUsersMock.buildList(2);
const response = await request(app.getHttpServer())
.get('/users')
.expect(200);
});
afterAll(async () => {
await app.close();
});
});
在单元测试中,您测试单个单元(服务、控制器等),这意味着您导入一个单元并模拟其所有依赖项。但是,在e2e测试中,您希望测试整个应用程序,因此应该导入根模块(
AppModule
),而不是单个单元或模块。有时,您可能希望模拟应用程序的特定部分,如数据库或第三方API;您可以使用overrideProvider
等来实现这一点
在您的情况下,您可能缺少从AppModule
导入MongooseModule
的forRoot
。导入AppModule,而不是重新构造应用程序的某些部分:
await Test.createTestingModule({
imports: [AppModule],
}).compile()
.overrideProvider(HttpService)
.useValue(httpServiceMock);
如果API受到保护,则需要对其进行身份验证。您可以通过编程方式创建JWT,也可以使用API。我假设您在以下示例中有一个用于身份验证的端点:
const loginResponse = await request(app.getHttpServer())
.post('/auth/login')
.send({ username: 'user', password: '123456' })
.expect(201);
// store the jwt token for the next request
const { jwt } = loginResponse.body;
await request(app.getHttpServer())
.get('/users')
// use the jwt to authenticate your request
.set('Authorization', 'Bearer ' + jwt)
.expect(200)
.expect(res => expect(res.body.users[0])
.toMatchObject({ username: 'user' }));
您好,谢谢您的回答,我用您的更改更新了问题(它可以工作),但保留我关于pass JwtAuthGuard的模拟jwt令牌的问题。谢谢@anthonywillismuñoz查看我的编辑。401错误与预期一样,因为您的API受到保护。测试未经验证的请求不能访问您的API实际上是一件好事。要测试受保护的资源,必须设置授权标头,请参见示例。此外,您不需要导入所有模块。仅导入AppModule。它本身将导入所有其他模块。@Kim Kern什么是httpServiceMock?我面临同样的问题,无法理解it@MegaRoks了解如何创建模拟的以下线程:
const loginResponse = await request(app.getHttpServer())
.post('/auth/login')
.send({ username: 'user', password: '123456' })
.expect(201);
// store the jwt token for the next request
const { jwt } = loginResponse.body;
await request(app.getHttpServer())
.get('/users')
// use the jwt to authenticate your request
.set('Authorization', 'Bearer ' + jwt)
.expect(200)
.expect(res => expect(res.body.users[0])
.toMatchObject({ username: 'user' }));