繁体   English   中英

如何清理 cypress cy.intercept 请求队列?

[英]How to cleanup cypress cy.intercept requests queue?

我正在使用在before(() => {...})块中编写的间谍 function 连续测试仪表板的几个过滤器(它们在后端):

function aliasQuery(
  request: CyHttpMessages.IncomingHttpRequest,
  operationName: string,
): void {
  const { body } = request;
  if (body.operationName === operationName) {
    request.alias = operationName;
  }
}

export function spyOnGraphQL(operationName: string): void {
  cy.fixture('hosts').then(({ graphQLHostname }) => {
    cy.intercept(ApiMethods.Post, graphQLHostname, (request) => {
      aliasQuery(request, operationName);
    });
  });
}

然后在for循环中我使用

cy.wait(`@${operationName}`).should(({response}) => {...})

逐一检查过滤器。

但是有麻烦,在使用每个过滤器并获得结果后,我需要通过发送另一个 graphql 请求来重置所有过滤器,该请求的查询名称与过滤器的查询名称匹配,因此当再次调用cy.wait时,它会捕获重置过滤器请求,这会破坏一切。它是这样的:

  • 应用过滤器 1(graphql 请求 1)
  • 使用cy.wait ,它捕获请求 1
  • 重置过滤器(graphql 请求 2)
  • 应用过滤器 2(graphql 请求 3)
  • 使用cy.wait ,它会捕获请求 2 --> 这就是问题开始的地方

有没有办法在应用新过滤器之前清理cy.intercept捕获的请求? 或者至少使用请求有效负载区分重置请求和过滤请求?

我没有找到清理请求队列的方法,但我可以使用额外的回调通过给它们不同的别名来忽略一些请求。

function aliasQuery(
  request: CyHttpMessages.IncomingHttpRequest,
  operationName: string,
  callback?: TypeAliasQueryCallback,
): void {
  const { body } = request;

  if (body.operationName === operationName) {
    request.alias = operationName;

    if (typeof callback === 'function') {
      callback(request);
    }
  }
}

export function spyOnGraphQL(
  operationName: string,
  callback?: TypeAliasQueryCallback,
): void {
  cy.fixture('hosts').then(({ graphQLHostname }) => {
    cy.intercept(ApiMethods.Post, graphQLHostname, (request) => {
      aliasQuery(request, operationName, callback);
    });
  });
}

export function ignoreResetRequest(
  request: CyHttpMessages.IncomingHttpRequest,
): void {
  const { body } = request;

  // Checking if the filters are sent (resetting sends empty array)
  if (!body.variables.filter.and.length) {
    request.alias = 'ignored';
  }
}

spyOnGraphQL('some_operation_name', ignoreResetRequest);

您可以使用times选项来确保您的拦截仅匹配一次,并在您期待请求时重新定义它。 例子:

cy.intercept({ url: /\/api\/.*\/path\/.*/, times: 1 }).as("fetchingMyData")
cy.wait("@fetchingMyData").then(() => { ... }) // the first wait


cy.intercept({ url: /\/api\/.*\/path\/.*/, times: 1 }).as("fetchingMyData2") // this resets the alias and the intercepted requests so that any request made before this point won't be considered.
cy.wait("@fetchingMyData2").then(() => { ... }) // the second wait

查看文档中的选项以获取更多信息: https://docs.cypress.io/api/commands/intercept#routeMatcher-RouteMatcher

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM