首页 > 解决方案 > NestJS 生命周期事件在 e2e 测试中未按预期执行

问题描述

我添加了一个服务来在应用程序启动和关闭时初始化一些示例数据。

@Injectable()
export class PostDataInitializerService
  implements OnModuleInit, OnModuleDestroy {
  private data: CreatePostDto[] = [
    {
      title: 'Generate a NestJS project',
      content: 'content',
    },
    {
      title: 'Create CRUD RESTful APIs',
      content: 'content',
    },
    {
      title: 'Connect to MongoDB',
      content: 'content',
    },
  ];

  constructor(
    @Inject(POST_MODEL) private postModel: Model<Post>,
    @Inject(COMMENT_MODEL) private commentModel: Model<Comment>,
  ) {}

  onModuleInit(): void {
    console.log('(PostModule) is initialized...');
    Promise.all(this.data.map((d) => this.postModel.create(d))).then((saved) =>
      console.log(saved),
    );
  }

  onModuleDestroy(): void {
    Promise.all([
      this.postModel.deleteMany({}),
      this.commentModel.deleteMany({}),
    ]).then((data) => {
      console.log(data);
    });
  }
}

有一个测试e2e来检查数据的数量,app.e2e-spec.ts#L26-L30)

    it('/posts (GET)', async () => {
      const res = await request(app.getHttpServer()).get('/posts').send();
      expect(res.status).toBe(200);
      expect(res.body.length).toEqual(3);
    });

但有时它有效,另一些则无效,初创公司的计数不是 3。

expect(received).toEqual(expected) // deep equality

    Expected: 3
    Received: 2

      27 |       const res = await request(app.getHttpServer()).get('/posts').send();
      28 |       expect(res.status).toBe(200);
    > 29 |       expect(res.body.length).toEqual(3);
         |                               ^
      30 |     });

另一次运行中的失败信息。

 expect(received).toEqual(expected) // deep equality

    Expected: 3
    Received: 1

      27 |       const res = await request(app.getHttpServer()).get('/posts').send();
      28 |       expect(res.status).toBe(200);
    > 29 |       expect(res.body.length).toEqual(3);
         |                               ^
      30 |     });
      31 | 
      32 |     it('/posts (GET) if none existing should return 404', async () => {

标签: jestjsnestjs

解决方案


推荐阅读