When using Cypress for automated testing, it is sometimes necessary to retrieve and save the HTML source of the currently accessed page. This can be achieved by combining Cypress's API with Node.js's file system (the fs module). Below is a step-by-step guide and code example:
-
First, ensure that Node.js and the
fsmodule are installed in your Cypress project. However, this is typically not required as Node.js is part of the Cypress runtime environment. -
In your Cypress test code, use the
cy.document()command to retrieve the current page's document object. -
Then, use
.invoke('documentElement.outerHTML')to retrieve the page's HTML source. -
Use the
cy.writeFile()command to write the retrieved HTML content to a file. Thecy.writeFile()command internally uses Node.js'sfsmodule to interact with the file system.
Here is a Cypress test code example that writes the current page's HTML source to a file:
javascriptdescribe('Save Page HTML Source', () => { it('Retrieve and Save Current Page HTML', () => { // Visit the page cy.visit('http://example.com'); // Retrieve the page's document object and its HTML source cy.document().invoke('documentElement.outerHTML').then((html) => { // Define the file path and filename to save const filePath = 'path/to/save/html-source.html'; // Write the HTML content to the file cy.writeFile(filePath, html); }); }); });
This code snippet first visits a URL using cy.visit(). Then it uses cy.document() to get the current page's document object and retrieves the entire page's HTML source via invoke('documentElement.outerHTML'). Finally, cy.writeFile() is used to write the HTML source to the specified file.
Please note that when writing test scripts, ensure the file path is correctly set and that your Cypress test environment has write permissions to the target path. Additionally, since writing files is an asynchronous operation, Cypress automatically handles the details related to asynchronous operations, making test script development simpler.