Puppeteer在测试中不会转到url(如何清除会话存储'sessionStorage未定义')



我正在为我的react网站使用jest puppeteer创建测试。当单独运行时,每个测试都通过,但当所有测试一起运行时,它们不会通过。

import './testFunctions'
import {
cleanSmokeTest,
testErrorsPage1,
testErrorsPages2,
} from '. /testFunctions'
describe('app', () => {
beforeEach(async () => {
jest.setTimeout(120000)
await page.goto('http://localhost:3000')
})
it('should for through all pages with no issue', async () => {
await cleanSmokeTest()
})
it('test errors on page 1', async () => {
await testErrorsPage1()
})
it('test errors on page 2', async () => {
await testErrorsPage2()
})

我对解决方案的最佳猜测是清除会话存储或在新页面中打开浏览器(因为如果页面已经通过一次,则不会发生错误(

以下内容不会打开网页url,所以我一直在思考如何解决这个问题

import './testFunctions'
import {
cleanSmokeTest,
testErrorsPage1,
testErrorsPages2,
} from '. /testFunctions'
describe('app', () => {
beforeEach(async () => {
jest.setTimeout(120000)
const puppeteer = require('puppeteer')
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('http://localhost:3000')
})
it('should for through all pages with no issue', async () => {
await cleanSmokeTest()
})
it('test errors on page 1', async () => {
await testErrorsPage1()
})
it('test errors on page 2', async () => {
await testErrorsPage2()
})

使用线路:

sessionStorage.clear()

产生错误

ReferenceError: sessionStorage is not defined

和:

window.sessionStorage.clear()

产生错误

ReferenceError: window is not defined

我认为您正在nodejs环境中运行sessionStorage.clear()函数。sessionStorage是在客户端javascript上下文中定义的。下面的代码正在页面上下文中执行该函数。

const html = await page.evaluate(() => {sessionStorage.clear() });

找到我的解决方案

await page.goto('http://localhost:3000')
await page.evaluate(() => {
sessionStorage.clear()
})
await page.goto('http://localhost:3000')

原因是除非到达页面,否则不会定义sessionStorage。一旦清除,页面就需要刷新,因为redux已经将其保存在内存中。

最新更新