簡體   English   中英

Puppeteer 在測試中不會轉到 url(如何清除會話存儲“sessionStorage 未定義”)

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

我正在使用 jest puppeteer 為我的 React 網站創建測試。 每個測試在單獨運行時都通過,但是當所有測試一起運行時它們不會通過。

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

我對解決方案的最佳猜測涉及清除會話存儲或在新頁面中打開瀏覽器(因為如果頁面已經通過一次,則不會發生錯誤)

以下不會打開網頁網址,所以我被困在如何解決這個問題上

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 已經將它保存在內存中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM