I am testing very basic REST api with supertest. I want to save the item id received in response body and assign it to a variable. Using this id i want to make further tests like get-item-by-id or update-item-by-id. No official documentation has covered this so a beginner friendly answer would be very helpful.
test i have written
JavaScript
x
22
22
1
const request = require("supertest")
2
let id;
3
4
describe('Products API', () => {
5
it('GET /products --> array of products', async () => {
6
return request('http://localhost:3001')
7
.get('/api/products')
8
.expect(200)
9
.expect('Content-Type', /json/)
10
.then(response => {
11
expect(response.body).toEqual(
12
expect.objectContaining({
13
success: true,
14
data: expect.any(Array)
15
})
16
)
17
})
18
})
19
20
})
21
22
Advertisement
Answer
Use regular JS variables
JavaScript
1
28
28
1
const request = require("supertest")
2
3
describe('Products API', () => {
4
it('GET /products --> array of products', async () => {
5
return request('http://localhost:3001')
6
.get('/api/products')
7
.expect(200)
8
.expect('Content-Type', /json/)
9
.then(response => {
10
expect(response.body).toEqual(
11
expect.objectContaining({
12
success: true,
13
data: expect.any(Array)
14
})
15
)
16
const data = response.body.data;
17
18
expect(data.length).toBeGreaterThan(0)
19
20
data.forEach(product => {
21
let id = product.id;
22
// expect data about the products
23
})
24
})
25
})
26
27
})
28
want to make further tests like get-item-by-id or update-item-by-id
You should explicitly test those endpoints, not via GET /api/products
E.g.
JavaScript
1
9
1
it('POST /products/{id} --> Updates a product', async () => {
2
const id = 1;
3
const result = request('http://localhost:3001')
4
.post(`/api/products/${id}`)
5
6
7
// TODO: Check the product was actually updated in the database, for example
8
});
9
More importantly, don’t (or try not to) store variable state between tests.