javascript - 在页面对象中使用 static(Cypress)
在浏览了各种在 Cypress 上实现端到端测试的示例后,我发现很多人使用创建新对象的方法,而不是使用 static。他们为什么这样做?为什么不对页面对象方法使用 static,因为我们并不修改类本身的任何数据,因此也不使用 this,而且也不需要拥有同一页面的多个实例(或者我没有看到使用它的场景)。我理解 Selenium 使用页面工厂,因此需要创建新对象,但在 Cypress 中我没有找到类似的情况。
创建新对象的示例:
import { BasePage } from './BasePageClass'
import { navMenu } from './NavigationMenuClass';
import { queryPage } from './QueryPageClass';
export class MainPage extends BasePage {
constructor() {
super();
this.mainElement = 'body > .banner';
}
verifyElements() {
super.verifyElements();
cy.get(this.mainElement).find('.container h1').should('be.visible');
}
switchToQueryingPage() {
navMenu.switchToQueryingPage();
queryPage.verifyElements();
}
};
export const mainPage = new MainPage();
使用 static 的示例:
import { BasePage } from './BasePageClass'
import { navMenu } from './NavigationMenuClass';
import { queryPage } from './QueryPageClass';
export default class MainPage extends BasePage {
static mainElement = 'body > .banner';
constructor() {
super();
}
static verifyElements() {
super.verifyElements();
cy.get(MainPage.mainElement).find('.container h1').should('be.visible');
}
static switchToQueryingPage() {
navMenu.switchToQueryingPage();
queryPage.verifyElements();
}
};
答案#1
这是一个我前辈教我使用的命令组合示例。我有一个函数buyProduct,但它需要几个步骤,我已经将它们分成不同的命令,可以在不同情况下使用:
it('buyProductAsCustomer', ()=>{
cy.login(customer)
cy.shopFe_openProductByName(product.name)
cy.shopFe_addProductToCart()
cy.shopFe_openCheckoutFromCart()
cy.shopFe_selectPaymentMethod("payWithCreditCardMethod")
cy.shopFe_fillCheckoutFormAsCustomer(customer)
cy.shopFe_checkoutPageGetOrderData()
cy.shopFe_submitCheckoutForm()
cy.shopFe_completePaymentWithCreditCard()
});
it('buyProductAsGuest', ()=>{
cy.shopFe_openProductByName(product.name)
cy.shopFe_addProductToCart()
cy.shopFe_openCheckoutFromCart()
cy.shopFe_selectPaymentMethod("payWithCashMethod")
cy.shopFe_fillCheckoutFormAsGuest(guest)
cy.shopFe_checkoutPageGetOrderData()
cy.shopFe_submitCheckoutForm()
cy.shopFe_completePaymentWithCreditCard()
});
这两种情况可以通过带有多个变量的命令来完成,但随着时间的推移,这些变量往往会增加十倍。因此,我们将它们分成可以以不同方式组合的小的可重复部分。
