[Cypress] Stub a Post Request for Successful Form Submission with Cypress

In this lesson well stub a POST request and use Cypress commands to fill in and submit a form. We’ll wait for the submission to resolve and then assert that the new item was added to the list.

For example when we dealing with Form submition, we want to issue a new POST request and then check it should update number of todos.

    it.only('should post new todo to the backend', function () {
        // Serve the page
        cy.server();

        // Prepare a POST request
        cy.route({
            method: 'POST',
            url: '/api/todos',
            response: {id: 123, name: 'new todo', isComplete: false}
        }).as('save');

        // Call a custom command to load initial todos
        cy.seedAndVisit();

        // Enter a new todo
        cy.get('.new-todo')
            .type('new todo')
            .type('{enter}');

        // Wait network request to be finished
        cy.wait('@save');

        // Calculate the expected length of todos
        cy.get('.todo-list li')
            .should('have.length', 5);
    });

// command
Cypress.Commands.add('seedAndVisit', (seedData = 'fixture:todos') => {
  cy.server()
  cy.route('GET', '/api/todos', seedData).as('load')

  cy.visit('/')

  cy.wait('@load')
});

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/9094594.html