Search code examples
javascriptnode.jsexpressmocha.jssupertest

Node: Mocha TDD sending Array in body


Below is the following body format I need to send in a request:

[{
  "user_id": "861",
  "username": "userA",
  "friend_id": "1270"
},
{
  "user_id": "861",
  "username": "userB",
  "friend_id": "1270"
}]

I created the following Test:

describe('POST /friends/add', () => {
    it('should return an array of Friend Objects ', (done) => {
        request(app)
            .post('/friend/add')
            .set('auth', token)
            .send([
                {
                    "user_id": authUserId,
                    "username": filteredUsers[0].username,
                    "friend_id": filteredUsers[0].id
                }, {
                    "user_id": authUserId,
                    "username": filteredUsers[2].username,
                    "friend_id": filteredUsers[2].id
                }, {
                    "user_id": authUserId,
                    "username": filteredUsers[3].username,
                    "friend_id": filteredUsers[3].id
                }
            ])
            .expect(200)
            .expect((res) => {
                expect(res.body.email).toBe(email)
            })
            .end((err, res) => {
                if (err) {
                    return done(err)
                }
                return done()
            })
    })
})

Question: is .send([{ }]) is creating the body parameter in the format mentioned above? an array of objects?


Solution

  • API you are using for test querying looks like SuperTest, which under the hood uses SuperAgent. Here is SuperAgent documentation for send.

    So yes, it will use your array, convert it into JSON and send it in body to your endpoint under test.