Search code examples
node.jscypressui-automatione2e-testingbrowser-automation

Wrong API on file-upload using Cypress.io for E2E testing


I am testing a portal with Cypress.io, which has a file upload functionality.

But my file always failed to upload because the API call is going wrong.

Correct API Call:
**

POST 200 /etl/v1.0.0/datauploaderetl/spaces/etl_jyddc0tx/data-files

**

But when uploading through Cypress, the following is the URL: **

POST 404 /etl/v1.0.0/datauploaderetl/data-files

** As you can clearly see, the API is incorrect. I added the wait here, still, it doesn't work. Following is the piece of code:

cy.fixture(fileName1).then(fileContent => {
        cy.get('input[type="file"]').attachFile({
            fileContent: fileContent.toString(),
            fileName: fileName1,
            mimeType: fileType
        })
    });
    cy.waitUntil(() => cy.get(":nth-child(98) > .modal > .modal-lg > .modal-content > .modal-body")
        .should('contain.text', 'Status: completed')
    );

This is how the modal looks like after uploading a file

Please help!


Solution

  • At Command.js, add below code:

    let LOCAL_STORAGE_MEMORY = {};
    
    Cypress.Commands.add("saveLocalStorage", () => {
        Object.keys(localStorage).forEach(key => {
            LOCAL_STORAGE_MEMORY[key] = localStorage[key];
        });
    });
    
    Cypress.Commands.add("restoreLocalStorage", () => {
        Object.keys(LOCAL_STORAGE_MEMORY).forEach(key => {
            localStorage.setItem(key, LOCAL_STORAGE_MEMORY[key]);
        });
    });
    

    Then at the test case file, add below beforeEach and afterEach block respectively:

     beforeEach(() => {
            cy.restoreLocalStorage();
        })
    
        afterEach(() => {
            cy.saveLocalStorage();
        })
    

    This will solve the issue where Cypress clears the "local storage" at the browser.