简体   繁体   English

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

[英]Puppeteer will not goto url in test (How to clear session storage 'sessionStorage is not defined')

I'm creating tests using jest puppeteer for my react website.我正在使用 jest puppeteer 为我的 React 网站创建测试。 Each test passes when run individually however they do not pass when all run together.每个测试在单独运行时都通过,但是当所有测试一起运行时它们不会通过。

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()
})

My best guess for a solution involves clearing the session storage or opening the browser in a new page (as no errors will occur if the page has already passed once)我对解决方案的最佳猜测涉及清除会话存储或在新页面中打开浏览器(因为如果页面已经通过一次,则不会发生错误)

The following will not open the webpage url so I'm stuck on how to solve this issue以下不会打开网页网址,所以我被困在如何解决这个问题上

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()
})

Using the line:使用该行:

    sessionStorage.clear()

produces the error产生错误

ReferenceError: sessionStorage is not defined

and:和:

window.sessionStorage.clear()

produces the error产生错误

ReferenceError: window is not defined

I think you are running sessionStorage.clear() function in nodejs environment.我认为您正在 nodejs 环境中运行sessionStorage.clear()函数。 sessionStorage is defined in client javascript context. sessionStorage 在客户端 javascript 上下文中定义。 The code below is executing the function in the page context.下面的代码在页面上下文中执行函数。

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

Found my solution找到我的解决方案

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

The reason for this was because sessionStorage is not defined unless the page is reached.这样做的原因是因为除非到达页面,否则不会定义 sessionStorage。 Once it has cleared the page needs a refresh because redux has kept it in memory.一旦它被清除,页面需要刷新,因为 redux 已经将它保存在内存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM