If you notice an additional row being added after the Submit action, it's recommended to verify that the row count has indeed increased by one.
Utilizing
.should('have.length', initialLength + 1)
will continuously recheck until a timeout is reached.
In some cases, the delay might not be due to timeout but could be related to background processing within the application. To accommodate this, consider including cy.wait(0)
.
cy.get('tr').then($current => {
const initialLength = $current.length;
cy.get('button').contains('Submit').click();
cy.wait(0); // for background processing in the app
cy.get('tr', {timeout: 10_000}).should('have.length', initialLength + 1)
cy.url().should("include", "/advertisers");
cy.get("tr").last().should("contain.text", "New Advertiser");
cy.get("tr").last().should("contain.text", "Lom Yolk");
cy.get("tr").last().should("contain.text", "500");
cy.get("tr").last().should("contain.text", "Prepaid");
})
Alternatively, another approach based on the example app provided below is:
Using cy.contains()
You can directly check for your form data without explicitly verifying the row count using cy.contains()
.
cy.get('button').contains('Submit').click();
cy.url().should("include", "/advertisers");
cy.contains("tr", "New Advertiser");
cy.contains("tr", "Lom Yolk");
cy.contains("tr", "500");
cy.contains("tr", "Prepaid");
Minimal reproducible example
Here is a basic web page scenario where clicking a button asynchronously adds a row to a table.
Upon pressing the button and checking the row count, the test should pass successfully.
Application Preview
<body>
<table>
<tbody>
<tr><td>one</td></tr>
<tr><td>two</td></tr>
</tbody>
</table>
<button>Add row</button>
<script>
const addButton = document.querySelector('button')
function addRow() {
setTimeout(() => {
const tableBody = document.querySelector('tbody')
const newRow = document.createElement('tr')
const newCell = document.createElement('td')
newCell.innerText = 'three'
newRow.appendChild(newCell)
tableBody.appendChild(newRow)
}, 2000)
}
addButton.addEventListener('click', addRow)
</script>
</body>
Testing Approach
cy.get('tr').then($tr => {
const initialRowCount = $tr.length
cy.get('button').click()
cy.get('tr').should('have.length', initialRowCount + 1)
cy.get('tr').last().should('contain.text', 'three')
})