jestjs - 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 () => {
解决方案
推荐阅读
- php - 移动和桌面探测器
- swift - 如何将数据连接到数组以在 TableView 中使用
- autodesk-forge - Autodesk Forge 提供的官方教程“查看您的模型”可以部署在真实的 Web 服务器上,而不是 localhost:3000 上吗?
- excel - 与使用 vba 的另一个 IP 范围列相比,如何过滤、复制和删除 IP 范围
- javascript - 有比使用 setInterval() 检测 JavaScript 中的类变量更改更好的方法吗?
- aframe - 隐藏实体,并找出 videosphere 中的错误
- python - 如何使用 UDP 获取的文字字节数据
- python - torch.nn.sequential 与多个 torch.nn.linear 的组合
- f# - 有没有办法追加到列表并同时增加列表的大小?
- python - 使用两个正则表达式加倍遇到问题