Last active
September 10, 2021 12:51
-
-
Save dr-skot/6189b01a71a31f0cf68a83819ac0dba9 to your computer and use it in GitHub Desktop.
Stub module imports in Cypress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cypress/support/commands.js | |
// ... | |
Cypress.Commands.add('visitWithStubs', (url, stubs) => { | |
if (!stubs) return cy.visit(url); | |
cy.visit(url, { | |
onBeforeLoad(win) { | |
Object.entries(stubs).forEach(([name, stubFunction]) => { | |
let target = undefined; | |
// attach getters and setters for this name on window | |
Object.defineProperty(win, name, { | |
// on set, stub the object | |
set: (object) => { | |
target = object; | |
stubFunction(target); | |
}, | |
// on get, return the stubbed object | |
get: () => target, | |
}); | |
}); | |
}, | |
}); | |
}); | |
// | |
// usage: | |
// | |
// in your code, expose the import on window | |
import ImportedThing from 'expensive-module'; | |
window.ImportedThing = ImportedThing | |
const result = ImportedThing.expensiveFunction() | |
// in your test, stub the function | |
describe('visitWithStubs', () => { | |
it('lets you stub stuff', () => { | |
cy.visitWithStubs('/path/to/somewhere', { | |
ImportedThing: (ImportedThing) => { | |
cy.stub(ImportedThing, 'expensiveFunction').returns(mockResult).as('stubbedFunction'); | |
}, | |
}); | |
cy.get('@stubbedFunction').should('have.been.called').and('have.returned', mockResult); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment