Cypress Testing Tips & Tricks

Share this post

Cypress secrets: cy.now and cy.state

cypresstips.substack.com

Cypress secrets: cy.now and cy.state

Advent day 17: Two internal Cypress commands that you should never use

Gleb Bahmutov
Dec 17, 2021
1
2
Share this post

Cypress secrets: cy.now and cy.state

cypresstips.substack.com

If you ever wanted to quickly run a Cypress command do I have a trick for you: use cy.now(commandName, arguments…) right from the browser DevTools console. For example, if the test finishes and I want to visit the base URL, I can:

Invoking the cy.visit command from the console

Nice! Notice the commands are logged at the end of the very last test in the Cypress Command Log.

The cy.now command returns a promise and cannot be chained to other Cypress commands and assertions as easily as during “normal” test, so it is not really suitable for building a Cypress REPL, but you can try.

The other secret internal Cypress command you should never use is cy.state() Just like Cypress.env() called without parameters it returns an object that has references to all internal objects used by the TestRunner. Often it is used by other Cypress commands to get the reference to the document and window objects via cy.state(‘document’) and cy.state(‘window’).

cy.state command returns an object with lots of internal references

So how could you take advantage of cy.now and cy.state in your code? By using them very carefully - these are internal commands and can change without warning. For example, I use these commands in cypress-data-session plugin to implement static methods of convenience: if the test is running (determined by looking at the cy.state), then the plugin code can run cy.task(…). If the test has finished already, the user can still call the method that in turn calls cy.now('task’, …) and still work. Read the blog post “Cypress internal commands cy.now and cy.state“ for all the gory details.

2
Share this post

Cypress secrets: cy.now and cy.state

cypresstips.substack.com
2 Comments
C Vera
Jan 12·edited Jan 12

Hi Gleb,

Is there a way to perform clicks with cy.now?

something like: cy.now('get', '.button','click') or cy.now('get', '.button').click()

Thanks in advance

Expand full comment
Reply
1 reply
1 more comment…
TopNewCommunity

No posts

Ready for more?

© 2023 Gleb Bahmutov
Privacy ∙ Terms ∙ Collection notice
Start WritingGet the app
Substack is the home for great writing