首页 > 解决方案 > 使用 TypeScript 在 Protractor 中正确导航页面对象

问题描述

我正在尝试使用 TypeScript 启动量角器测试套件,但我遇到了 pageObjects 链接问题,我不确定如何解决或以更好的方式完成。我见过的任何示例都不会处理多个页面。

我将简化示例文件以便于帮助,当我实例化新的页面对象时,这个问题似乎集中在我身上,但我不确定如何以更好的方式做到这一点。有人能指出我正确的方向吗?

basePageObject.ts

import { browser, by, element, ExpectedConditions } from 'protractor';
import {NextPageObject} from './nextPageObject';

export class BasePage {

async navigateTo() {
 await browser.get('http://localhost:8080');
}

async launchThing() {
 await element(by.css('#launchThing')).click();
}

async clickNavToNextPage(): Promise<NextPageObject> {
 await element(by.css('#nextPageNav')).click();
 return new NextPageObject();
}
}

nextPageObject.ts

import { browser, by, element, ExpectedConditions } from 'protractor';

export class NextPageObject {

private firstNameField = element(by.css('.testFirstName'));

async getFirstName(): Promise<string> {
 return await this.firstNameField.getAttribute("value");
}

async enterFirstName(firstName: string): Promise<NextPageObject> {
 await this.firstNameField.clear();
 await this.firstNameField.sendKeys(firstName);
}

}

测试规范.ts

import { browser, by, element } from 'protractor';
import { BasePage } from 'basePageObject';

const expectedName = "Peter";

fdescribe('Navigation with custom URL', function() {
let page: BasePage;

beforeEach(async () => {
 page = new BasePage();
 await page.navigateTo();
});

fit('page nav', async function() {
 await page.navigateTo(url);

 const next1 = await page.clickNavToNextPage();
 expect(element(by.css('body > next-page- 
 header')).isPresent()).toBe(true);

 await next1.enterFirstName("Peter");

 // this fails as an empty string is returned but is close to the way 
 //I want to do things
 const firstNameFieldValue = await next1.getFirstName();
 expect(await firstNameFieldValue).toEqual(expectedName);


 // this works but is not how I want to do it
 const elementval = element(by.css('.testFirstName'));
 expect(elementval.getAttribute('value')).toEqual(expectedName);

}
}

标签: angulartypescriptprotractorautomated-testspageobjects

解决方案


尝试更改此行:

private firstNameField = element(by.css('.testFirstName'));

至:

private get firstNameField() { return element(by.css('.testFirstName')); }

element()在您发送密钥之前调用第一个版本。在第二个版本中,它在您发送密钥后被调用。


推荐阅读