cypress-documentation
cypress-documentation copied to clipboard
Document cy.state and why you'd use it
Related to: https://github.com/cypress-io/cypress/issues/467
Yes, please!
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!`)
}
}
})
}
Hi @jennifer-shehane @bahmutov is there any plan to document this? Or at least provide typings?
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.
cy.state()
is also shown in the custom queries documentation, but its type is not exposed.
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) : ???
}
}
}