如何使用守卫nestjs进行e2e

ant*_*ñoz 5 javascript node.js typescript jestjs nestjs

我想 e2e 使用 Nestjs 调用的端点/users,但出现错误。我怀疑如何通过警卫的测试。

第一个错误

Nest 无法解析 UserModel 的依赖关系(?)。请确保索引 [0] 处的参数 DatabaseConnection 在 MongooseModule 上下文中可用。

第二个错误

预期 200“OK”,得到 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 });
  }
}
Run Code Online (Sandbox Code Playgroud)

用户服务

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

控制器

@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;
    }
Run Code Online (Sandbox Code Playgroud)

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();
  });
});

Run Code Online (Sandbox Code Playgroud)

Kim*_*ern 12

在单元测试中,您测试单个单元(服务、控制器等),这意味着您导入一个单元并模拟其所有依赖项。然而,在 e2e 测试中,您想要测试整个应用程序,因此您应该导入根模块 ( AppModule) 而不是单个单元或模块。有时您可能想要模拟应用程序的特定部分,例如数据库或第 3 方 API;你可以用overrideProvideretc来做到这一点

就您而言,您可能错过了forRootMongooseModule您的AppModule. 导入 AppModule,而不是重构应用程序的某些部分:

await Test.createTestingModule({
      imports: [AppModule],
    }).compile()
      .overrideProvider(HttpService)
      .useValue(httpServiceMock);
Run Code Online (Sandbox Code Playgroud)

如果您的 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' }));
Run Code Online (Sandbox Code Playgroud)