是否可以 return 或等待 return 的柏树拦截?

Is it possible to return or await for return of cypress intercept?

我想在 运行 e2e 测试时获得拦截 cypress 调用的响应:

const registerUser = async (username, password)=>{
    cy.visit('<user_registration_url');
    
    cy.intercept('/registration').as('registration');
    
    
    cy.get('input#username').type(username);
    cy.get('input#password').type(password);
    cy.get('button#submit').click()
    
    // Expected response:
    //{statusCode: 200, body: {userId: <string>}}
    const result = await cy.wait('@registration');
    const userId = result.response.body.userId;
    return userId

it('should test something with a newly registered user', ()=>{
    const userId = registerUser('foobar', 'password');
    // ... keep testing using the userId which was generated on the backend.
});

不,这行不通。

Cypress 是异步的,因此这些命令不会 return 您可以分配给变量的任何数据。您可以在 Cypress docs.

中阅读更多内容

你可以这样得到回复:

cy
  .wait('@registration')
  .then(response => {
    // some other code
  });

或者您可以检查例如像这样的状态代码:

cy
  .wait('@registration')
  .its('response.statusCode')
  .should('eq', 201);

您可以在 cy.intercept command 的页面上看到许多示例。

所以确实正如@pavelsman 提到的那样,柏树没有 async/await 语法。为了使效用函数可以 return 可链接,如本例所示:

const registerUser = (username, password)=>{
    cy.visit('<user_registration_url');
    
    cy.intercept('/registration').as('registration');
    
    
    cy.get('input#username').type(username);
    cy.get('input#password').type(password);
    cy.get('button#submit').click()
    
    // Expected response:
    //{statusCode: 200, body: {userId: <string>}}
    return cy.wait('@registration');


it('should test something with a newly registered user', ()=>{
    registerUser('foobar', 'password').then(result=>{
        const userId = result.response.body.userId;
        // ... keep testing using the userId which was generated on the backend.
    });
});