My test is querying a JSON and put value to 'text' variable, but when trying to use the variable I'm getting an error:
cy.type() cannot accept an empty string. You need to actually type something
How can I use the text I got from the query? here is the code:
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);
})
})
@Konrad is nearly correct, you need to return both the cy.request()
and the result of the following .then()
.
But unfortunately you can't use async/await on Cypress commands as they do not return Promises, they return Chainer objects.
This is how you can adjust the code
const WebApiRequests = {
url: "https://api.jsonbin.io/v3/b/62e129e3248d43754f074152",
makeRequest: function (method, url, body) {
return cy // return the Chainable (it's not a promise)
.request({
method: method,
url: url,
body: body,
})
.then((response) => {
return response.body["record"][0]["team"]; // return the modified response
});
},
};
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, "")
// use then to unwrap the Chainable
.then(text => {
QueryingPage.inputNameObject().type(text); // passes
})
});
});