运行 Playwright Test 时页面未定义问题

问题描述 投票:0回答:1

我是剧作家新手。当使用对象实例调用不同类中的方法时,抛出错误“页面未定义”。

代码如下: 页面.test.ts

 import { expect } from "@playwright/test";
    import { Page } from "playwright-core";
    
    export class petStoreLoginPage {
        
        private page: Page;
            constructor (page : Page) {
            this.page = page
        }
        
        //Locators
    
        eleSignIn = async () => await this.page.$("text=Sign In")
    
        eleUserNm = async () => await this.page.$("input[name='username']")
    
        elePwd    = async () => await this.page.$("input[name='password']")    
    
        eleLogin  = async () => await this.page.$("input[value='Login']") 
    
        eleWelcomeScreen = async () => await this.page.waitForSelector("div[id='WelcomeContent']")
    
        eleSignOut = async () => await this.page.$("text=Sign Out")
    }
    
    actions.test.ts
    import { expect, Page } from '@playwright/test'
    import {petStoreLoginPage} from '../Pages/pt.page'
    
    declare const page : Page
    let userInOut : petStoreLoginPage = new petStoreLoginPage(page)
    
    export class userInOutAction  {
       
        public async clickSignIn() {
            
            const ele = await userInOut.eleSignIn()
            if (ele != null)    
                await ele.click()
            else throw new Error("No element found")
        }
    
        public async clickSignOut() {
            const ele = await userInOut.eleSignOut()
            if (ele != null)
                await ele.click()
            else throw new Error("No element found")
        }
    
        public async enterUserNm(userNm : string) {
            const ele = await userInOut.eleUserNm()
            if (ele != null)
                await ele.fill(userNm)
            else throw new Error("No element found")
        }
    
        public async enterPwd(pwd : string) {
            const ele = await userInOut.elePwd()
            if (ele != null)
                await ele.fill(pwd)
            else throw new Error("No element found")
        }
    
        public async clickLogin() {
            const ele = await userInOut.eleLogin()
            if (ele != null)
                await ele.click()
            else throw new Error("No element found")
        }
    
        public async verifyHomePage() {
            const ele = await userInOut.eleWelcomeScreen()
            if (ele != null)
                expect(await ele.innerText()).toBe("Welcome cgtdemo!")
             else throw new Error("Welcome page not landed!!!")
        }
    
        public async verifyLoginLogoutPage() {
            const ele = await userInOut.eleSignIn()
            if (ele != null)
                expect(await ele.innerText()).toBe("Sign In")
            else throw new Error("Welcome page not landed!!!")
        }
    
    }

test1.test.ts

import {  test } from '@playwright/test';
import Environment from '../Environment/environment';
import {userInOutAction} from '../Actions/pt.actions'



test("TC01 - Login and Logout Petstore Application", async ({page}) => {

    let login : userInOutAction =  new userInOutAction()

    await test.step("Step 1 - Go to PetStore Application and Click SignIn", async () => {
        await page.goto(Environment.test);
        await login.clickSignIn();
        await login.verifyLoginLogoutPage();
    })
    await test.step("Step 2 - Enter username and password", async () => {
        await login.enterUserNm("cgtdemo");
        await login.enterPwd("cgtdemo");
    })
    
    await test.step("Step 3 - userInOutAction to PetStore Application", async () => {
        await login.clickLogin()
        await login.verifyHomePage()
      })
    await test.step("Step 4 - Signout the PetStore Application", async () => {
        await login.clickSignOut()
        await login.verifyLoginLogoutPage()
      })
  })   
  test.afterAll(async({page}) => 
{
        await page.close()
  })

在进行 npx playwright test 时,得到 ReferenceError: page is not Defined。能够知道这是因为页面调用正确,但我在代码中没有看到任何问题,也没有抛出任何错误。

automation playwright
1个回答
0
投票

当我尝试保存单击按钮获取无效表单/ReferenceError:“页面未定义”时,我也面临此类问题

异步填充客户表单(客户数据){ this.logger.info('正在填写客户详细信息');

    try {
        // Wait for the file input element to be visible
        await this.page.waitForSelector("#fileInput");

        // Set the file input (assuming the file path is correct)
        await this.page.setInputFiles("#fileInput", "C:\\Users\\sathishd\\Downloads\\EtihadAirways.jpg");
        await this.page.waitForTimeout(2000);

        // Fill in the form inputs and select dropdown options
        await this.page.fill('(//input[@id="organizationName"])[1]', customerData.customerName);
        await this.page.getByLabel('Short Name').click();
        await this.page.getByLabel('Short Name').fill('SPR');
       // await this.page.fill("(//input[@id='shortName'])[1]", customerData.shortName);
        await this.page.fill("(//input[@id='shortName'])[2]", customerData.customerECode);
        await this.page.selectOption("(//select[@id='opucode dropdown-toggle'])[2]", customerData.customerType);
        await this.page.waitForTimeout(2000);
        await this.page.fill("(//input[@type='text'])[5]", customerData.ICAO);
        await this.page.fill("(//input[@type='text'])[6]", customerData.IATA);
        await this.page.waitForTimeout(2000);

        // Click on the date picker input and set the date
        await this.page.click('#ej2-datepicker_0 input');
        await this.page.fill("(//input[@id='ej2-datepicker_0_input'])[1]", customerData.InductionDate);

        // Select user-defined category from a dropdown
        await this.page.selectOption("(//select[@id='opucode dropdown-toggle'])[3]", customerData.userdefinedCategory);
        await this.page.waitForTimeout(2000);

        try {
            // Wait for the save button to be visible and clickable
            
            await this.page.waitForSelector('button:has-text("Save")', { visible: true, timeout: 5000 });
            
            // Click the save button
            //await this.page.click('button:has-text("Save")');
            await this.page.getByRole('button', { name: 'Save' }).first().click({ force: true });
           // await page.getByRole('button').click({ force: true });
            this.logger.info('Save button clicked successfully');
        } catch (error) {
            this.logger.error(`Error clicking save button: ${error}`);
        
            // Attempt to capture a screenshot for debugging
            try {
                const screenshotPath = 'C:/sathish/AiDocx_Automation_Plywrt02/screenshot/save_button_error.png';
                await this.page.screenshot({ path: screenshotPath });
                this.logger.info(`Screenshot captured: ${screenshotPath}`);
            } catch (screenshotError) {
                this.logger.error(`Error capturing screenshot: ${screenshotError}`);
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.