如何在赛普拉斯中设置本地存储
How to set local storage in cypress
我有一个简单的测试
describe('Page Test', () => {
it('button has "contact-next-disabled" class', () => {
cy.get('.contact-next-disabled')
})
})
但是运行测试后,cypress报错
34 | useEffect(() => {
35 | const _contact = getLocalStorage()
> 36 | if (!_contact.categories.length && !_contact.categoryNameEtc) {
| ^
37 | PGToaster.showDanger('Please select a category.')
38 | router.push('/contact/a-type')
39 | }
我的 getLocalStorage
函数与我正在测试的函数位于不同的文件中
export const getLocalStorage = () => {
const contact = JSON.parse(window.localStorage.getItem('contact'))
return contact
}
与我的 setLocalStorage
函数一起工作
export const setLocalStorage = (contact) => {
const _contact = getLocalStorage()
const updateContact = {
..._contact,
...contact
}
window.localStorage.setItem('contact', JSON.stringify(updateContact))
}
如果我重写
if (!_contact.categories.length && !_contact.categoryNameEtc)
到
if (!_contact?.categories.length && !_contact?.categoryNameEtc)
错误消失了,但我只想在我的 cypress 测试中设置本地存储,而不是重写我的代码。我该怎么做?
的文档
Cypress automatically runs this command before each test to prevent state from being shared across tests. You shouldn't need to use this command unless you're using it to clear localStorage inside a single test.
您可以使用 hooks
:
设置您的测试
before(() => {
// set localStorage
})
或者您可以使用 cypress-localstorage-commands 之类的插件在 Cypress 测试之间保留 localStorage。
我有一个简单的测试
describe('Page Test', () => {
it('button has "contact-next-disabled" class', () => {
cy.get('.contact-next-disabled')
})
})
但是运行测试后,cypress报错
34 | useEffect(() => {
35 | const _contact = getLocalStorage()
> 36 | if (!_contact.categories.length && !_contact.categoryNameEtc) {
| ^
37 | PGToaster.showDanger('Please select a category.')
38 | router.push('/contact/a-type')
39 | }
我的 getLocalStorage
函数与我正在测试的函数位于不同的文件中
export const getLocalStorage = () => {
const contact = JSON.parse(window.localStorage.getItem('contact'))
return contact
}
与我的 setLocalStorage
函数一起工作
export const setLocalStorage = (contact) => {
const _contact = getLocalStorage()
const updateContact = {
..._contact,
...contact
}
window.localStorage.setItem('contact', JSON.stringify(updateContact))
}
如果我重写
if (!_contact.categories.length && !_contact.categoryNameEtc)
到
if (!_contact?.categories.length && !_contact?.categoryNameEtc)
错误消失了,但我只想在我的 cypress 测试中设置本地存储,而不是重写我的代码。我该怎么做?
Cypress automatically runs this command before each test to prevent state from being shared across tests. You shouldn't need to use this command unless you're using it to clear localStorage inside a single test.
您可以使用 hooks
:
before(() => {
// set localStorage
})
或者您可以使用 cypress-localstorage-commands 之类的插件在 Cypress 测试之间保留 localStorage。