我想使用 Nestjs e2e 一个名为 /users
的端点,但出现错误。我很怀疑如何让测试通过守卫。
第一个错误
Nest can't resolve dependencies of the UserModel (?). Please make sure that the argument DatabaseConnection at index [0] is available in the MongooseModule context.
第二个错误
expected 200 "OK", got 401 "Unauthorized"
应用程序模块
@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;
}
}
Controller
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService, private readonly utilsService: UtilsService) { }
@Get()
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
async users() {
const users = await this.usersService.getAllUsers();
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();
});
});
最佳答案
在单元测试中,您测试单个单元(服务、 Controller 等),这意味着您导入一个单元并模拟其所有依赖项。但是,在 e2e 测试中,您想要测试整个应用程序,因此您应该导入根模块 (AppModule
),而不是单个单元或模块。有时您可能想要模拟应用程序的特定部分,例如数据库或第 3 方 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' }));
关于javascript - 如何使用守卫nestjs进行e2e,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359414/