简体   繁体   English

使用 await cypress 避免回调不起作用?

[英]avoid callback with await cypress doesn't work?

I have alias on my fixture stub, so this is working for me:我的夹具存根上有别名,所以这对我有用:

describe("some page", () => {
  beforeEach(() => {
    cy.intercept("/users", {
      fixture: users.json,
    });
    cy.visit("/somewhere");
  });

  it("show something", () => {
    cy.wait("@firstApiCall").then(() => {
      cy.wait("@2ndApiCall").then(() => {
        cy.get("test:something").should("exist");
      });
    });
  });
});

but this won't work?但这行不通?

it("show something", () => {
  await cy.wait("@firstApiCall");
  await cy.wait("@firstApiCall");

  cy.get("test:something").should("exist");
});

Also, how can I avoid repeating cy.wait(apiCall) in each it block?另外,如何避免在每个it块中重复cy.wait(apiCall)

It probably fails with:它可能会失败:

Unexpected reserved word 'await'.

and that's because await keyword could be used only in async functions, your callback function is not async.那是因为await关键字只能在async函数中使用,您的回调 function 不是异步的。

You might write:你可能会写:

it("show something", async () => {
  await cy.wait("@firstApiCall");
  await cy.wait("@firstApiCall");

  cy.get("test:something").should("exist");
});

But I wonder why do you want to do it?但我想知道你为什么要这样做? Cypress does a good job running the commands in the order in which they are written ( https://docs.cypress.io/guides/core-concepts/introduction-to-cypress#Commands-Run-Serially ).赛普拉斯很好地按照编写顺序运行命令( https://docs.cypress.io/guides/core-concepts/introduction-to-cypress#Commands-Run-Serially )。

I also doubt your example actually works:我也怀疑你的例子是否真的有效:

describe("some page", () => {
  beforeEach(() => {
    cy.intercept("/users", {
      fixture: users.json,
    });
    cy.visit("/somewhere");
  });

  it("show something", () => {
    cy.wait("@firstApiCall").then(() => {
      cy.wait("@2ndApiCall").then(() => {
        cy.get("test:something").should("exist");
      });
    });
  });
});

You don't alias firstApiCall and 2ndApiCall , so Cypress doesn't know what to wait for.您没有别名firstApiCall2ndApiCall ,因此赛普拉斯不知道该等待什么。

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

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