Cypress 中的文字驗證


Cypress 可以藉助 jQuery text() 方法驗證元素上的文字。這種方法會幫助我們獲取所選元素上的文字內容。我們還可以對元素的文字內容進行斷言。

cy.get('.product').should('have.text', 'Tutorialspoint');

我們可以在文字上進行驗證,例如驗證它包含什麼或使用 Javascript 方法 match()、include() 等進行匹配。因此,Cypress 命令可以利用 jQuery 物件對非 Cypress 方法進行操作,並呼叫它們上的方法。

示例

使用 text() 方法實現程式碼。

// test suite
describe('Tutorialspoint Test', function () {
// test case
it('Test Case1', function (){
// test step to launch a URL
cy.visit("https://tutorialspoint.tw/index.htm");
// enter test in the edit box
// assertion to validate the number of child elements
cy.get('#gs_50d > tbody > tr > td'). should('have.length',2);
// locate element with get and find method
cy.get('#gs_50d > tbody > tr > td'). find('input')
//enter test in the edit box
.type('Cypress');
//iterate the list items with each command
cy.get('.mui-tabs__bar.mui-tabs__bar_1.mui-tabs__bar--justified)
.find('li').each(($el, index, $list) => {
// extract text with text() method
const txt = $el.find('a').text();
if ( txt.includes('Deve')){
$el.click();
}
})
});
});

執行上述程式碼塊後,Cypress 測試執行程式會給出以下輸出 −

更新於:05-Aug-2020

7 千次觀看

啟動你的 事業

完成課程並獲得認證

開始學習
廣告