英文:
How can I call the api repeatedly in supertest?
问题
I want to test create, findById, and GetList that express api.
And I want to call create api repeatedly for test getlist function.
But If I use for loop syntax, that occurred TCPWRAP error.
How can I call the api repeatedly in supertest?
test("Make Some Products (10)", (done) => {
for(let i=0;i<10;i++) {
agent
.post(`/api/product`)
.send({
...productJson,
title: productJson.title + String(i),
})
.expect(200)
.end((err, res) => {
if(err) throw err;
expect(res.body.success).toBeTruthy();
productIds.push(PRODUCT_ID);
});
}
done();
});
英文:
I want to test create, findById, and GetList that express api.
And I want to call create api repeatedly for test getlist function.
But If I use for loop syntax, that occurred TCPWRAP error.
How can I call the api repeatedly in supertest?
test("Make Some Products (10)", (done)=> {
for(let i=0;i<10;i++) {
agent
.post(`/api/product`)
.send({
...productJson,
title: productJson.title + String(i),
})
.expect(200)
.end((err, res) => {
if(err) throw err;
expect(res.body.success).toBeTruthy();
productIds.push(PRODUCT_ID);
});
}
done();
});
答案1
得分: 1
1- 据我所知,这不是编写测试的正确方式。
2- 如果要测试create
函数,那么无需使用循环。只需要一次调用即可。
3- 如果要测试getList
函数,那么在填充数据库时不应使用expect()
。您只需要使用expect()
来检查getList
的返回值。
4- 更好的填充数据库的方式是在Jest的beforeEach()
中使用数据库模块的方法(例如mongoose的model.save()
)。
beforeEach(() => {
// 插入记录并保存它们的ID在productIds中
});
test("getList", (done) => {
// 使用上面插入的数据来测试您的API
})
英文:
As far as I know, this is not the correct way of writing tests.
1- If you want to test create
function, then there is no need for the loop. Only one call is adequate.
2- If you want to test getList
function, then you should not use expect() when you are populating the database. You only need expect() to check the return value of your getList
.
3- A better way to populate database is to use your database module's methods (for example mongoose's model.save()
) in jest's beforeEach()
.
beforeEach(() =>{
// insert records and save their ids in productIds
});
test("getList", (done) =>{
// test your api using the data inserted above
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论