簡體   English   中英

賽普拉斯:使用 cy.intercept() 檢查是否尚未進行調用?

[英]Cypress: Using cy.intercept() to check if a call hasnt been made yet?

使用 cy.intercept() 攔截(和存根)幾個 .network 請求(到 google 標簽管理器),但想在我期望它們被調用之前在我的測試的早期進行測試。

我將如何測試我正在攔截的 2 條路線尚未被調用?

謝謝!

您可以利用cy.spy命令:

cy.intercept('/my-route', cy.spy().as('myRequest'));

// later in the test

cy.get('@myRequest').should('not.have.been.called'); // not yet intercepted

// something triggers the API call

cy.get('@myRequest').should('have.been.calledOnce'); // now is intercepted

請參閱: https://docs.cypress.io/api/commands/spy
歸功於:https://glebbahmutov.com/blog/cypress-tips-and-tricks/#check-if-the.network-call-has-not-been-made

Intercept 有一個 routeHandler 部分,可以是 function

cy.intercept(routeMatcher, routeHandler ?)

routeHandler(字符串 | object | Function | 靜態響應)

function 收到請求,在里面另一個 function 可以收到響應,
請參閱攔截響應

cy.intercept('/integrations', (req) => {
  // req.continue() with a callback will send the request to the destination server
  req.continue((res) => {
    // 'res' represents the real destination response
    // you can manipulate 'res' before it's sent to the browser
  })
})

因此,在收到req或內部 function 收到res時,設置一個外部標志並在測試中的一個或多個位置對其進行測試,

// top of the test

let interceptFlag = false;

cy.intercept('/my-route', (req) => {
  interceptFlag = true;
  req.continue((res) => {
    // or here
    interceptFlag = true;
  })
})

// later in the test

cy.wrap(interceptFlag).should('eq', false);   // not yet intercepted

// something triggers the API call

cy.wrap(interceptFlag).should('eq', true);    // now is intercepted

這是非常籠統的,如果您發布一些細節可以更具體。

暫無
暫無

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

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