Skip to content

Instantly share code, notes, and snippets.

@adamdehaven
Last active January 27, 2022 00:32
Show Gist options
  • Save adamdehaven/74d82b76eb36a3ee00a78843bb8f67b6 to your computer and use it in GitHub Desktop.
Save adamdehaven/74d82b76eb36a3ee00a78843bb8f67b6 to your computer and use it in GitHub Desktop.
Cypress component tests: stub window methods (only relevant code)
import Login from 'Login.vue'
import win from 'window.ts'
it('pre-populates the email input from search params', () => {
// Stub search params
cy.stub(win, 'getLocationSearch').returns(`?email=${encodeURIComponent(user.email)}`)
mount(Login)
// Email input should be pre-populated
cy.getTestId(testids.email).should('have.value', user.email)
})
import win from 'window.ts'
setup () {
onMounted(async () => {
// Get URL params
const urlParams = new URLSearchParams(win.getLocationSearch())
// Set email if in route params
const emailInParams = urlParams?.get('email')
if (emailInParams) {
formData.email = emailInParams
}
}
}
// Using a function to retrieve window.location properties so it can be stubbed in Cypress component tests
const win = {
getLocationSearch: (): string => {
if (typeof window === 'undefined') return ''
return window.location.search
},
getLocationHostname: (): string => {
if (typeof window === 'undefined') return ''
return window.location.hostname
},
getLocationHref: (): string => {
if (typeof window === 'undefined') return ''
return window.location.href
},
getLocationPathname: (): string => {
if (typeof window === 'undefined') return ''
return window.location.pathname
},
getLocationOrigin: (): string => {
if (typeof window === 'undefined') return ''
return window.location.origin
},
setLocationHref: (url: string): void => {
if (typeof window === 'undefined') return
window.location.href = url
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment