在 Cypress 中获取 HTML table 的数据
Get data of HTML table in Cypress
我想 return table 使用 Cypress
(没有 Cy 包装器)的人类可读格式的数据。
假设我们有这样一个table:
Col1
Col2
Col3
D1
D3
D5
D2
D4
D6
这是我的代码,但我不知道如何获取真实数据:
getTableData() {
return cy.get('#table-modal')
.then(modal => cy.wrap(modal).find('table > tbody > tr'))
.each(row =>
cy
.wrap(row)
.find('td')
.each(column => cy.wrap(column).invoke('text'))
);
}
const expected = [
['D1', 'D3', 'D5'],
['D2', 'D4', 'D6']
];
getTableData().should('eq', expected); // failing, because function returns wrapped data by Cypress
尝试:
async function getTableData() {
const table = (await cy.get("table")).get(0);
const data = Array.from(table.querySelectorAll("tr")).map((tr) =>
Array.from(tr.children).map((td) => td.textContent)
);
return data;
}
const expected = [
["Col1", "Col2", "Col3"],
["D1", "D3", "D5"],
["D2", "D4", "D6"],
];
cy.wrap(getTableData()).should("deep.eq", expected);
我想 return table 使用 Cypress
(没有 Cy 包装器)的人类可读格式的数据。
假设我们有这样一个table:
Col1 | Col2 | Col3 |
---|---|---|
D1 | D3 | D5 |
D2 | D4 | D6 |
这是我的代码,但我不知道如何获取真实数据:
getTableData() {
return cy.get('#table-modal')
.then(modal => cy.wrap(modal).find('table > tbody > tr'))
.each(row =>
cy
.wrap(row)
.find('td')
.each(column => cy.wrap(column).invoke('text'))
);
}
const expected = [
['D1', 'D3', 'D5'],
['D2', 'D4', 'D6']
];
getTableData().should('eq', expected); // failing, because function returns wrapped data by Cypress
尝试:
async function getTableData() {
const table = (await cy.get("table")).get(0);
const data = Array.from(table.querySelectorAll("tr")).map((tr) =>
Array.from(tr.children).map((td) => td.textContent)
);
return data;
}
const expected = [
["Col1", "Col2", "Col3"],
["D1", "D3", "D5"],
["D2", "D4", "D6"],
];
cy.wrap(getTableData()).should("deep.eq", expected);