I have a function in Cypress support/index.js that is meant to get the dimensions of the cy.document
outerWidth
and outerHeight
, then return them for future use in a test. My problem is that when the test runs and the values are compared with others the assertion says the values are NaN
. I checked by console logging the value at the point of the assertion and it was empty, so I must be doing something wrong, I'm just not sure what. My function is below, any help gratefully received, thanks.
function getViewport() {
var viewport = {}
cy.document().then((doc) => {
let width = Cypress.$(doc).outerWidth()
let height = Cypress.$(doc).outerHeight()
viewport['bottom'] = height
viewport['height'] = height
viewport['left'] = 0
viewport['right'] = width
viewport['top'] = 0
viewport['width'] = width
viewport['x'] = 0
viewport['y'] = 0
}).then(() => {
return viewport
})
return viewport
}
The code that calls getViewport()
is
export const getRect = (obj) => {
var rect
if (obj == 'viewport') {
rect = getViewport()
} else {
rect = getElement(obj)
if (Cypress.config('parseLayoutToInt')) { rect = parseAllToInt(rect) }
}
return rect
}
And that is called by a custom command, where subject
is prevSubject
and the element is the string "viewport"
Cypress.Commands.add('isInside', { prevSubject: true }, (subject, element, expected) => {
var minuend, subtrahend, diff
minuend = getRect(element)
subtrahend = getRect(subject)
diff = getRectDiff(minuend, subtrahend, expected);
expect(diff).to.deep.equal(expected);
})
I ran into this problem as well, and opted for a solution with async/await:
Even though Cypress commands aren't really promises, you can create your own promise, and resolve it when ready. Then
await
that promise in your test code.Hope it helps!
Like @NoriSte said, the
cy
commands are asynchronous thus you can't mix them with sync code.What you want to do is something like:
Anyway, to answer the original question (in the title), there's a couple of patterns I use to store a value for later use in cypress:
wrap next commands in the
then
callback:cache to a variable and access the cached value from inside an enqueued command:
Ad the actual problem in your question (if I understood it correctly), I've made a solution you can learn from:
Why there is a synchronous return in your
getViewport
function? I'm speaking about the lastreturn viewport
doing so, all the
cy.document().then((doc)
etc. code is useless.I don't know if this is the problem, but I can't run your code locally because it misses a lot of functions. Could you share a "working” GitHub repo to make some more tests?