I’m trying to setup my beforeEach
to create a new email if none exist before starting my tests, but when I try to count how many emails there are in my beforeEach
, it always logs as 0
, even if there are more. If I log the count
in my it
block, it shows the correct count.
Does this look correct? How can I properly check the count
in the beforeEach
so that it doesn’t always create a new email for every test?
JavaScript
x
23
23
1
describe("email", () => {
2
beforeEach(() => {
3
cy.visit("/");
4
5
let count = Cypress.$('#emails').length
6
7
// always logs 0
8
cy.log(count)
9
10
if(count == 0) {
11
createNewEmail()
12
}
13
});
14
15
it("email", () => {
16
let count = Cypress.$('#emails').length
17
18
// logs correct amount
19
cy.log(count)
20
});
21
});
22
23
Advertisement
Answer
Cypress commands are asynchronous. So when the test executes cy.visit("/")
it does not mean that the next line will be executed after the page gets really loaded.
You can fix this as follows:
JavaScript
1
11
11
1
beforeEach(() => {
2
cy.visit("/").then(() => {
3
let count = Cypress.$('#emails').length
4
cy.log(count)
5
if(count == 0) {
6
createNewEmail()
7
}
8
})
9
}
10
11