mercredi 25 novembre 2020

How to post sequential POST requests in TestCafe?

I am trying to set up an automated ui test in TestCafe. It is in three parts.

The UI part (which is the last part) is straightforward and not a problem. It is confirming and closing alerts that has come in to an account. But to set off that alert I need to perform two api post requests.

The first one is logging in and retrieving the bearer token.

The second one is posting the alert using the bearer token for authorization.

If I only post the login request I get the token returned. And if I hard code the bearer token in the second request - it works perfectly.

I have googled to try and find any help and the only found suggestions for sequential get requests. I have tried that, but in doing that the second request is always run first - and then the test fails on a 401 response.

Below you have the code I have tried to run. Any suggestions would be greatly appreciated

let axios = require('axios');
var token = ''

let login = "http://url/login"
let alert = "http://url/alarm"

const firstRequest = axios.post(login ,
{
  'email': 'email@gmail.com',
  'password': 'pwd'
}
  .then((response) => {
    console.log(response)
    token = response.data.token
    return token 

  })
  .catch(error => {
    console.error(error)
  }))


const secondRequest = axios.post(alert, 
{
  deviceId: 29152
  },
  {
    headers: 
    {
      'Authorization': `Bearer ${token}`
    },
})

axios
  .all ([firstRequest, secondRequest])
  .then(
    axios.spread((...responses) => {
      const firstResponse = responses [0];
      const secondResponse = responses [1];

      console.log(firstResponse, secondResponse);
    })
  )
  .catch(errors => {
      console.error(errors)
  });

Aucun commentaire:

Enregistrer un commentaire