Last active
January 27, 2022 00:32
-
-
Save adamdehaven/74d82b76eb36a3ee00a78843bb8f67b6 to your computer and use it in GitHub Desktop.
Cypress component tests: stub window methods (only relevant code)
This file contains 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
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) | |
}) |
This file contains 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
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 | |
} | |
} | |
} |
This file contains 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
// 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