In my cypress test I'm trying to store contents of id_px_file_input
-field and then use it a part of cy.contains()
cy.get('[id=id_px_file_input]').then(new_id => {
const tableID = new_id;
cy.wrap(tableID).as('tableID');
});
cy.contains('Hakemisto').click()
cy.wait(10000)
cy.contains(`U ${'@tableID'} -`).click()
cy.wait(10000)
Where the input looks like this:
<input type="text" name="px_file_input" value="13bu" class="form-control" placeholder="" maxlength="400" disabled="" id="id_px_file_input">
and '13bu' is the value I want to store in "variable" tableID
.
After clicking "Hakemisto" I want to test that the page contains an element with text U 13bu -
How can I do it ?
Use the static
option when saving the tableId. This preserves the actual value, does not re-query if "Hakemisto" click re-writes the page.
Use invoke('val')
to get the actual value, the element is not useful in .contains()
.
Then retrieve the value after the click, use it in next .contains()
.
Finally move wait(10_000) to timeout on the last click, so you're not waiting more than is necessary.
cy.get('[id=id_px_file_input]')
.invoke('val') // value of input element, not the element itself
.as('tableId', { type: 'static' }); // static alias storage
cy.contains('Hakemisto').click()
cy.get('@tableId').then(tableID => { // retrieve value
cy.contains(`U ${tableId} -`, {timeout: 10_000}).click() // timeout 10 seconds
})
There is a package bahmutov/cypress-aliases that lets you unwrap aliases directly in the .contains()
selector.
So this should work
import 'cypress-aliases'
it('my test description', () => {
cy.get('[id=id_px_file_input]').invoke('val')
.as('tableId', { type: 'static' });
cy.contains('Hakemisto').click()
cy.contains('@tableId'), {timeout: 10_000}).click()
})