我正在为基于 React 的 Web 工具编写测试。所以我想在每次测试之前清除所有本地存储,例如登录信息等。我主要在 Cypress 工作,这只是一个简单的命令。
cy.clearLocalStorage();
我现在正在使用 WebdriverIO,这是我正在尝试的方法(在测试文件中)。
afterEach(() => {
browser.executeScript('window.localStorage().clear()');
});
但是,这似乎不起作用。此外,我更喜欢一个全局解决方案,这样我不必在每个测试中都编写一些东西。预先感谢您的帮助。
来自 WebdriverIO 文档:
// remove the storage item for the given key
client.localStorage('DELETE', 'someKey');
// clear the storage
client.localStorage('DELETE');
您可以通过运行此预设功能来清除本地存储。
你的假设几乎是正确的。我建议使用官方文档来消除小错误。
而不是
executeScript
使用 https://webdriver.io/docs/api/browser/execute.html
localStorage
不是函数,请参阅 https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
应该是这样
afterEach(() => {
browser.execute('window.localStorage.clear()');
});
附注 假设您使用的是 WebdriverIO 5 或更高版本。
所以,经过很长时间,我们意识到了问题所在。
cy.clearLocalStorage()
仅清理 baseUrl
定义下的本地存储。
如果您想打开多个页面,则必须在
cy.visit()
调用中显式定义清除,如下所示:
cy.visit(`subdomain.another.domain`, {
onBeforeLoad(win) {
win.localStorage.clear();
},
});
在这种情况下,确切域的本地存储将被删除。
我希望这个解决方法有帮助。
您需要在 Wdio 中做什么来复制 cy.clearLocalStorage() 就是下面这个
//异步
await browser.reloadSession()
//同步
browser.reloadSession()
例如,可以像这样应用以再次登录,而无需先前会话存储的缓存:
beforeEach( async function () {
if(this.currentTest._currentRetry != 0) {
await browser.reloadSession()
}
}
或者用它来测试回访用户:
//Get URL before abandoning the flow
const currentURL = await browser.getUrl()
//Clear local storage application
await browser.reloadSession()
//Navigate back to the flow
await browser.navigateTo(currentURL)
//Authenticate from the page the user left
await basePage.authenticateMethod(user)