Reputation: 1
I have been testing an API. Now I am getting the API response in HTML format where I have table data (without table name) and under the i have ahref tag and test. I have to validate the ahref text fro the response body.
So anyone has any idea that will really helpful for me.
I tried:
cy.wrap(res.body).get('table').contains('td','textname')
but getting timeout error.
Upvotes: 0
Views: 3059
Reputation: 31904
To test the HTML from response with Cypress commands, you need to write and visit it so that Cypress thinks it's a legit web page
cy.writeFile('./cypress/fixtures/fragment.html', html)
.then(() => { // writing is async so wait for it to complete
cy.visit('./cypress/fixtures/fragment.html')
cy.get('table').contains('td','textname')
})
Should be done in a separate it()
block to avoid conflicts with you main app page.
Otherwise you can follow @agoff's pattern and use dom.querySelector()
to query the data.
Upvotes: 1
Reputation: 7125
You can use JavaScript's DOMParser
to parse your string into a DOM variable.
it('tests something', () => {
// Declare the DOMParser
const parser = new DOMParser();
cy.request('/foo').then((res) => {
// Parse the string (in this case, the response body) as a `text/html` object.
const dom = parser.parseFromString(res.body, 'text/html');
// use document functions below to traverse the dom
});
});
Upvotes: 2