使用 Cypress 處理 Web 表格
可以使用 Cypress 處理 Web 表格。Web 表格可以分為兩種型別:靜態和動態。靜態 Web 表格的行數和列數是固定的。而動態 Web 表格的行數和列數則不是固定的。
為了在表格中識別特定列的值,我們需要藉助 CSS 選擇器。表格結構的 HTML 由 <table> 標籤、<tr> 標籤和 <td> 標籤組成。行由 <tr> 表示,列值由 <td> 表示。
藉助 CSS 中的 nth-child 概念,我們可以識別特定列的所有值。例如,對於一個有兩列的表格,為了獲取第一列的所有值,CSS 應該為 tr td:nth-child(1)。下面顯示了表格 HTML 結構示例:
現在,要檢索同一行下一列單元格中的值,我們必須移動到第二列。在 Cypress 中,我們有 next() 命令可以移動到 DOM 中緊跟其後的兄弟節點。next() 命令只有與 get() 命令一起使用時才有效。
語法
.next() , without arguments. .next(selector/options), with argument. next(selector, options), with arguments.
如下所示,可能有兩種型別的選項可以修改 .next() 命令的預設行為:
log – log 的預設值為 true。
timeout – timeout 引數的預設值為 defaultCommandTimeout(4000 毫秒)。這是等待 .next() 完成的持續時間。
示例
處理 Web 表格的程式碼實現。
describe('Tutorialspoint Test', function () { // test case it('Test Case4', function (){ cy.visit("https://tutorialspoint.tw/plsql/plsql_dbms_output.htm"); // identify the second column for all the rows cy.get('.table.table-bordered > tbody > tr > td:nth-child(1)').each(($el, index, $list) => { // grabbing all text from second column const txt = $el.text(); // checking the matching condition if (txt.includes('1')){ // capturing the next sibling with the help of next() method cy.get('.table.table-bordered > tbody > tr > td:nth-child(1)') .eq(index).next().then(function(desc){ // capturing the text of next sibling const rsl = desc.text(); //assertion to verify the text expect(rsl).to.contains('DBMS_OUTPUT.DISABLE'); }) } }) }); });
上面程式碼實現中使用的 Web 表格:
廣告