I have a custom cypress command which performs some asynchronous tasks, and based on the result of the command I want to perform some assertions
But the problem is the tests that come after calling the command will either run before the command finishes or will have wrong values.
below is my code
Command
Cypress.Commands.add("testCommand", () => {
cy.request("http://localhost:3000/testApi").then(({ body }) => {
cy.request(`http://localhost:3000/testApi${body.query}`).then(() => {
console.log("success");
});
});
});
test
describe("Summary Page", () => {
it("my demo test", () => {
console.log("before command runs");
cy.testCommand();
console.log("after command runs");
});
});
Actual result
before command runs
after command runs
success
Required result
before command runs
success
after command runs
as you can see the output after command runs will run before the command finished
Is there any way to wait for the command to complete before moving forward with tests
CodePudding user response:
It's due to the fact that non-cypress commands runs asynchronously meaning it will not necessarily run the commands in sequence in which it is written. To tackle this you can use then(), something like:
describe('Summary Page', () => {
it('my demo test', () => {
console.log('before command runs')
cy.testCommand().then(() => {
console.log('after command runs')
})
})
})
CodePudding user response:
If console.log() is not necessary, then you can replace with cy.log(), which will log to the test runner. That way you can replace at the exact locations without altering too much of you code.
Command
Cypress.Commands.add("testCommand", () => {
cy.request("http://localhost:3000/testApi").then(({ body }) => {
cy.request(`http://localhost:3000/testApi${body.query}`).then(() => {
// you may want to add some assertion here, maybe expected status code
cy.log("success");
});
});
});
test
describe("Summary Page", () => {
it("my demo test", () => {
cy.log("before command runs");
cy.testCommand();
cy.log("after command runs");
});
});
