superagent / supertest with async / await

Gobliins picture Gobliins · Jul 20, 2018 · Viewed 8k times · Source

Goal is to set the variable auth correctly for further use, hence i want to refactor the function loginUser:

function loginUser(user, request, auth) {
  return function(done) {
    request
      .post('/users/login')
      .send(credentials)
      .expect(200)
      .end(onResponse);

    function onResponse(err, res) {
      auth.token = res.body.token;
      return done();
    }
  };
}


 loginUser(user, request, auth)(function() {
  request.get(testUrl)
    .set('Authorization', `bearer ${auth.token}`)
    .expect(200, done);
});

to use async / await like this (without the callback):

auth = await loginUser(user, request);
request.get(testUrl)
    .set('Authorization', `bearer ${auth.token}`)
    .expect(200, done);

But i am struggling of returning / setting auth correctly (it would not matter if i pass auth as parameter or as return value).

What i tried was stuff like this:

async function loginUser(user, request) {
  let auth;
  await request
    .post('/users/login')
    .send(credentials)
    .expect(200)
    .end(onResponse);

  function onResponse(err, res) {
    auth.token = res.body.token;
  }
  return auth;
}

But auth was never set correctly.

Answer

Lev Kuznetsov picture Lev Kuznetsov · Jul 20, 2018

Don't use 'end' syntax, that's for callbacks:

const response = await request.post(...)
  .expect(200)
const {body: {token}} = response
return token

Basically it should look like sync code