Cypress:使用 cy.intercept() 检查是否尚未进行调用?

Ky *_*ane 6 javascript testing cypress

使用 cy.intercept() 拦截(和存根)几个网络请求(到谷歌标签管理器),但希望在我的测试中尽早进行测试,然后再期望它们被调用。

我如何测试我正在拦截的两条路由尚未被调用?

谢谢!

fse*_*dev 13

您可以利用以下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
Run Code Online (Sandbox Code Playgroud)

请参阅: https: //docs.cypress.io/api/commands/spy
致谢:https://glebbahmutov.com/blog/cypress-tips-and-tricks/#check-if-the-network-call-has -未制作


小智 3

Intercept 有一个routeHandler 部分,它可以是一个函数

cy.intercept(routeMatcher,routeHandler?)

RouteHandler(字符串|对象|函数|静态响应)

该函数接收请求,其中另一个函数可以接收响应,
请参阅拦截响应

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
  })
})
Run Code Online (Sandbox Code Playgroud)

因此,无论是在收到req或在收到 的内部函数时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
Run Code Online (Sandbox Code Playgroud)

这个很笼统,如果你发布一些细节可以更具体。