cypress-documentation icon indicating copy to clipboard operation
cypress-documentation copied to clipboard

Document cy.state and why you'd use it

Open jennifer-shehane opened this issue 6 years ago • 6 comments

Related to: https://github.com/cypress-io/cypress/issues/467

jennifer-shehane avatar Sep 25 '17 16:09 jennifer-shehane

Yes, please!

Threnos avatar Mar 13 '20 14:03 Threnos

I use this method for checking that a specific request did not happen. For example: test of dialog that creates user. Clicking button "Add user" starts form validation process, which highlights falsy inputs and shakes dialog box. Metod requestNotOccurred() is invoked after click on a button to test that validation works correctly and user is not created without required inputs.

type HttpMethods = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
type RequestsMap = 'userAdd' // helps with intellisense. Actually, this is a string literal union, here is a single entry for example simplicity

const requestsMap: { // holds technical information about request
  [K in RequestsMap]: {
    method: HttpMethods
    url: string
  }
} = {
  userAdd: {
    method: 'PUT',
    url: '**/User/Add'
  }
}

/**
 * Checks that no request occurred to a specified url
 * @param {RequestsMap} alias - alias of request
 * @example
 *
 * cy.get('[data-cy="users_addUserDialog_btnAddUser"]').click()
 * requestNotOccurred('userAdd')
 */
export function requestNotOccurred(alias: RequestsMap): Cypress.Chainable<null> {
  return cy.log(`Check that request "${alias}" didn't happen`).then(() => {
    for (const happenedRequest of cy.state('requests')) {
      if (
        happenedRequest.xhr.method === requestsMap[alias].method &&
        Cypress.minimatch(happenedRequest.xhr.url, requestsMap[alias].url, {
          matchBase: true
        })
      ) {
        throw new Error(`Request "${alias}" happened!`)
      }
    }
  })
}

Threnos avatar Jun 28 '21 14:06 Threnos

Hi @jennifer-shehane @bahmutov is there any plan to document this? Or at least provide typings?

shwarcu avatar Nov 16 '21 12:11 shwarcu

The Cypress website's "Test Retries" guide includes an example usage of cy.state. This inclusion warrants either a warning about its usage with TypeScript or an offering in the public API with accompanying typings.

jaredasutton avatar Jul 28 '22 22:07 jaredasutton

cy.state() is also shown in the custom queries documentation, but its type is not exposed.

dwightjack avatar May 23 '23 08:05 dwightjack

Is creating typings for cy.state within the scope of this ticket because that is also needed?

Also, is there a workaround to add it ourselves pending the release of this? I know you can add this bit, but not sure what it should return:

declare global {
  namespace Cypress {
    interface Chainable {
      state(state: string) : ???
    }
  }
}

verheyenkoen avatar Feb 29 '24 08:02 verheyenkoen