-1

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();
    });
DW_Cod
  • 35
  • 5
  • `await` each request? Then you can get rid of the somewhat archaic `done` function - see https://jestjs.io/docs/asynchronous. – jonrsharpe May 14 '23 at 13:39

1 Answers1

1

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
})
mohsen dorparasti
  • 8,107
  • 7
  • 41
  • 61