I have now ended up doing something like this: ``...
# best-practices
g
I have now ended up doing something like this:
Copy code
ts
And('when we are make a requests to the barrthrill api', () => {
  const url = `${constants.baseUrl.api}/barrythrill/user/123455`.trim();
  const pathToSign = Helper.getPathToSign(url );
  const timeStamp = Helper.formatDateISOBasic(new Date());

  const headers = [
    { name: 'provider', value: 'thrill' },
    { name: 'key', value: '12345' },
    { name: 'environment', value: 'DevTest' },
    { name: 'timestamp', value: timeStamp },
  ];

  const corndog = {};
  Object.entries(headers).forEach(([, header]) => { corndog[header.name] = header.value; });

  cy.task('ThrillSignature', { pathToSign, headers }).then((signature) => {
    cy.request({
      url: url ,
      method: 'GET',
      headers: {
        ...corndog,
        'signature': signature,
      },
      failOnStatusCode: false,
      log: true,
    })
      .then((response) => {
        cy.log('resp', JSON.stringify(response));
      });
  });
});
Do you have any other suggestions on how I could perhaps improve?
f
What's your reasoning behind using
cy.task()
? That seems a little redundant to me
g
the reason of cy.task is that im doing some signatures "behind the scene" to be able to perform a request to my API
so e.g. in this case that would be
Copy code
ts
async ThrillSignature({ pathToSign, headers }) {
  const signer = new MessageSigner();
  const signature = signer.getSignature('barrythrill', pathToSign, headers, []);
  return signature;
},
and that piece of code will always remain the same so it will never be changed to all my test
while the cy.request can be different for each test.
f
Got it. Only other thing I wonder about is your use of
failOnStatusCode: false
. You're presumably going to be asserting on the response in some other way?
Or retrying the call until it's successful?
g
I will do some asserting if it fails. 😄
(because its not supposed to fail but you never know) 😄
f
You've also got the
cypress-wait-until
or
cypress-recurse
plugins so that you can retry until you get a success response
g
The only thing it could fail is that if you enter wrong URL or headers basically
and if that happens then its a big issue on the API which shouldnt happend 😄
so therefore I use it
But what I wonder is that if I could somehow perhaps improve this code
Or do you think this is good enough?
f
I don't see any issue with it, tbh
You could shorten
url: url,
to just
url,
in your call to
cy.request()
but that's nitpicking
g
oh thats true,
But otherwise it looks good
I was just afarid if this is more like
"Not related to cypress test"
that I should not do this inside a test basically
f
Nah. I don't like abstracting things for the sake of it. I want to try and make tests as readable as possible, and part of that is making sure that maintainers aren't having to hop between lots of files
g
Yeah then in thtat case this would be pretty neat
6 Views