vue.jscypressamazon-cognitocypress-component-test-runner

Intercept network request in Cypress component test


In Cypress e2e test, I was using cy.intercept to intercept a graphql call and make it return mocked response.

Now I am trying to do the same in my Vue component test (mount the component, take some action to make a call to occur) but it seems doing nothing, a call ends up getting null response.

Wonder if I need some setup to make this working? (I'm using Cypress@10.7.0)

const queryName = 'myQuery'
const aliasName = aliasGraphqlName('Query', queryName)
const responseMyQuery = { "data": { ... } }

// beforeEach
    cy.intercept('POST', graphqlUrl, (req) => {
      aliasGraphqlQuery(req, queryName)

      if (req.alias && req.alias === aliasName) {
        req.reply(responseMyQuery)
      }
    })

// my test
    cy.mount(MyComponent, {...})
    cy.get('[data-test=myField] button.mdi-pencil')
      .click() // api call gets null not responseMyQuery

Solution

  • My app was using AWS Cognito for user authentication and to be able to make a graphql call, user should be logged in. For component test, it needs a way to login programmatically.

    Cypress has a guide on Amazon Cognito Authentication.

    After adding loginByCognitoApi command, my test looks like below and working ok with mocked response:

    // component.js
    import Amplify, { Auth } from 'aws-amplify'
    import awsmobile from '~/aws-exports'
    Amplify.configure(awsmobile)
    Cypress.Commands.add('loginByCognitoApi', (username, password) => {
    ...
    
    // beforeEach
        cy.intercept('POST', graphqlUrl, (req) => {
          aliasGraphqlQuery(req, queryName)
    
          if (req.alias && req.alias === aliasName) {
            req.reply(responseMyQuery)
          }
        })
        cy.loginByCognitoApi(
          existingUser,
          existingUserPassword
        )
    
    // my test
        cy.mount(MyComponent, {...})
        cy.get('[data-test=myField] button.mdi-pencil')
          .click() // api call gets responseMyQuery