簡體   English   中英

在 Cypress 組件測試中攔截網絡請求

[英]Intercept network request in Cypress component test

在賽普拉斯 e2e 測試中,我使用cy.intercept攔截 graphql 調用並使其返回模擬響應。

現在我試圖在我的 Vue 組件測試中做同樣的事情(安裝組件,采取一些行動來進行調用)但它似乎什么也沒做,一個調用最終得到 null 響應。

想知道我是否需要一些設置才能使其正常工作? (我使用的是 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

我的應用程序使用 AWS Cognito 進行用戶身份驗證並能夠進行 graphql 調用,用戶應該登錄。對於組件測試,它需要一種以編程方式登錄的方法。

Cypress 有關於Amazon Cognito 身份驗證的指南。

添加loginByCognitoApi命令后,我的測試如下所示,並且可以使用模擬響應:

// 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM