如何在supertest中重复调用API?

huangapple go评论55阅读模式
英文:

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(&quot;Make Some Products (10)&quot;, (done)=&gt; {
        for(let i=0;i&lt;10;i++) {
            agent
            .post(`/api/product`)
            .send({
                ...productJson,
                title: productJson.title + String(i),
            })
            .expect(200)
            .end((err, res) =&gt; {
                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(() =&gt;{
    // insert records and save their ids in productIds
});

test(&quot;getList&quot;, (done) =&gt;{
    // test your api using the data inserted above
})

huangapple
  • 本文由 发表于 2023年5月14日 21:36:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76247750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定