简体   繁体   中英

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. 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. sessionStorage is defined in client javascript context. 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. Once it has cleared the page needs a refresh because redux has kept it in memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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