Cypress.require
Cypress.require
enables utilizing dependencies within the
cy.origin()
callback function. It is used to require
modules such as npm packages and other local files.
It is functionally the same as using
CommonJS require()
in browser-targeted code.
Syntax
Cypress.require(moduleId)
Usage
Correct Usage
cy.origin('somesite.com', () => {
const _ = Cypress.require('lodash')
const utils = Cypress.require('./utils')
// ... use lodash and utils ...
})
Incorrect Usage
// `Cypress.require()` cannot be used outside the `cy.origin()` callback.
// Use `require()` instead
const _ = Cypress.require('lodash')
cy.origin('somesite.com', () => {
// `require()` cannot be used inside the `cy.origin()` callback.
// Use `Cypress.require()` instead
const _ = require('lodash')
})
// the callback must be inline and cannot be assigned to a variable for
// `Cypress.require()` to work
const callback = () => {
const _ = Cypress.require('lodash')
})
cy.origin('somesite.com', callback)
Examples
See
cy.origin()
Dependencies / Sharing Code
for example usages.
Limitations
Cypress.require
only works when called within thecy.origin()
callback function. It will error if used elsewhere.Cypress.require
only works in conjunction with the webpack preprocessor, which is the default preprocessor for Cypress. If you have manually installed and configured the webpack preprocessor, ensure you are using version5.13.0
or greater.- For
Cypress.require
to work, the callback function must be written inline with thecy.origin()
call. The callback cannot be assigned to a variable.
History
Version | Changes |
---|---|
10.7.0 | Cypress.require added |