I am trying to integration test an API endpoint to return a specific user data by attaching the userId to the endpoint
I am currently able to test the endpoint that returns all users however when I try to write a test to return specific user data by attaching the user's id to the route I just end up testing the route returning all users.
describe('User profile route', () => {
let token = '';
let userId = '';
let userId1 = '';
useInTest();
it('should return a specific user details', (done) => {
signUp(mockData.signUpData).expect(201)
.end(() => {});
signUp(mockData.signUpData1).expect(201)
.end(() => {});
login(mockData.loginData)
.expect(200)
.end((err, res) => {
token = res.body.accessToken;
userId = res.body.user._id;
});
agent.get(`/api/users/${userId1}`).set('Authorization', 'Bearer ' + token)
.expect(200)
.end((err, res) => {
console.log(res.body);
res.body.should.have.length(1);
done();
})
});
}
I expect that test to pass but unfortunately, it doesn't simply it keeps hitting the this api/users
instead of hitting this api/users/:id
I think this is not a supertest issue. How about you make test asynchronous because by the time your test makes a request the userId could be undefined since it is set after login. Try updating you code like this(add words in asterisks):
it('should return a specific user details', **async**(done) => {
signUp(mockData.signUpData).expect(201)
.end(() => {});
signUp(mockData.signUpData1).expect(201)
.end(() => {});
**await** login(mockData.loginData)
.expect(200)
.**then**((err, res) => {
token = res.body.accessToken;
userId = res.body.user._id;
});
agent.get(`/api/users/${userId1}`).set('Authorization', 'Bearer ' + token)
.expect(200)
.end((err, res) => {
console.log(res.body);
res.body.should.have.length(1);
done();
})
});