javascript 全局变量未更新[重复]

pbpqsu0x  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(282)
    • 此问题在此处已有答案**:

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference(7个答案)
How do I return the response from an asynchronous call?(45个答案)
1小时前关闭。
我的测试是查询JSON并将值放入'text'变量,但当尝试使用该变量时,我得到了一个错误:
cy. type()不能接受空字符串。您需要实际键入一些内容
如何使用从查询中获得的文本?下面是代码:

var text = ''

const WebApiRequests = {
    url : 'https://api.jsonbin.io/v3/b/62e129e3248d43754f074152',
    
    makeRequest : function(method, url, body){
    cy.request({
      method: method,
      url: url,
      body: body
    }).then((response) => {
        text = response.body['record'][0]['team'];
    });
    }
}

const QueryingPage = {
    
    inputNameObject : function(){
        return cy.get('#inputName');
    }
}

describe('Navigate to Querying page', () => {
  it('Visits the Cypress website and clicks on the Querying menu', () => {
    cy.visit('https://example.cypress.io/commands/querying');
    WebApiRequests.makeRequest('GET', WebApiRequests.url, '');
    QueryingPage.inputNameObject().type(text);
    });
  });
hyrbngr7

hyrbngr71#

此代码应如下所示:

const WebApiRequests = {
  url: "https://api.jsonbin.io/v3/b/62e129e3248d43754f074152",

  makeRequest: function (method, url, body) {
    // return the promise
    return cy
      .request({
        method: method,
        url: url,
        body: body,
      })
      .then((response) => {
        return response.body["record"][0]["team"];
      });
  },
};

const QueryingPage = {
  inputNameObject: function () {
    return cy.get("#inputName");
  },
};

describe("Navigate to Querying page", () => {
  // make the callback function async
  it("Visits the Cypress website and clicks on the Querying menu", async () => {
    cy.visit("https://example.cypress.io/commands/querying");
    // await for the text
    const text = await WebApiRequests.makeRequest(
      "GET",
      WebApiRequests.url,
      ""
    );
    QueryingPage.inputNameObject().type(text);
  });
});

相关问题