Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let Cypress return custom errors or messages

I'm looking for a way to create a custom message instead of the standard messages. What I have is this piece of code (scrambled a bit):

Cypress.Commands.add('authenticate', {prevSubject: 'optional'}, (_, fixture) => {
  return cy.fixture(fixture).then(credentials => {
    cy
      .apiRequest('scrambled/url/here', {
        method: 'post',
        authorizationMethod: 'Basic',
        token: apiOauthSecret,
        data: credentials
      })
      .then(resp => {
        expect(resp.status)
          .to
          .eq(201, 'Unable to authenticate, login failed')
        storeTokenInSession(resp.body)
      })
  })
})

That code results in a error like this: https://i.stack.imgur.com/l2j4o.png

If I fix the code so the result is okay the result looks like this: https://i.stack.imgur.com/Pr1iA.png

As you see the message should be displayed if the eq() fails instead of when the eq() succeeds.

I want to show the message only if the check fails, but I also want the test to break and stop.

Do you people have any idea how to get this working? I already looked into using cy.log() and the solution shown here.

like image 317
Mr. J. Avatar asked Feb 18 '19 13:02

Mr. J.


People also ask

Why is Cypress returning an error instead of a warning?

The reason this is an error instead of a warning is because Cypress internally queues commands serially whereas Promises execute as soon as they are invoked. Attempting to reconcile this would prevent Cypress from ever resolving. Cypress detected that you returned a promise in a test, but also invoked one or more cy commands inside of that promise.

Why can't I return a promise from a cypress command?

Because Cypress commands are already promise-like, you don't need to wrap them or return your own promise. Cypress will resolve your command with whatever the final Cypress command yields. The reason this is an error instead of a warning is because Cypress internally queues commands serially whereas Promises execute as soon as they are invoked.

Why does my Cypress test fail when I return a string?

Even though we return a string in our test, Cypress automatically figures out that you've queued commands above and does not end the test until all cy commands have finished. The example below will fail because you've forcibly terminated the test early with mocha's done.

Should I wrap or return my Cypress commands?

Because Cypress commands are already promise-like, you don't need to wrap them or return your own promise. Cypress will resolve your command with whatever the final Cypress command yields.


1 Answers

You can use Cypress.log for that:

if (resp.status !== 201) {
  Cypress.log({
    name: 'Authentication',
    message: 'failed'
  })
}
expect(resp).its('status').eq(201)
like image 96
bkucera Avatar answered Sep 23 '22 13:09

bkucera