【问题标题】:ClassSerializeInterceptor in Nest.JS Unit TestsNest.JS 单元测试中的 ClassSerializeInterceptor
【发布时间】:2020-02-05 04:20:10
【问题描述】:

在测试 Nest.JS 控制器时是否可以使用 ClassSerializeInterceptor?

我们的问题是 ClassSerializeInterceptor 作为应用程序的一部分可以正常工作,但在控制器作为单元测试的一部分实例化时无法运行。我尝试将 ClassSerializeInterdeptor 作为测试模块的一部分提供,但没有成功。

示例代码:

测试

describe('AppController', () => {
  let appController: AppController;

  beforeEach(async () => {
    const app: TestingModule = await Test.createTestingModule({
      controllers: [AppController],
      providers: [AppService,  ClassSerializerInterceptor],
    }).compile();

    appController = app.get<AppController>(AppController);
  });

  describe('root',  () => {
    it('should not expose exlcuded fields"', async  () => {

      // expect(appController.getHello()).toBe('Hello World!');

      const s = await appController.getHello();

      expect(s).toHaveProperty('shouldBeIncluded');
      expect(s).not.toHaveProperty('shouldBeRemoved');

    });
  });
});

测试实体:

@ObjectType()
@Entity()
export class TestEntity {

  @Field(type => ID)
  @PrimaryGeneratedColumn('uuid')
  shouldBeIncluded: string;

  @Column({ nullable: true })
  @Exclude()
  shouldBeRemoved: string;
}

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    测试拦截器作为请求流的一部分只能在 e2e 和部分集成测试中完成。您需要将supertest 实例设置为described in the docs 并发送请求以确保ClassSerializeInterceptor 按预期运行。

    【讨论】:

      猜你喜欢
      • 2020-05-23
      • 2021-04-05
      • 1970-01-01
      • 2023-03-16
      • 2020-04-14
      • 2021-09-08
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多