Skip to content

Commit a421c55

Browse files
authored
add example wrapping async function in custom command (#424)
1 parent 94ae974 commit a421c55

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

examples/fundamentals__add-custom-command/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ And the TypeScript and IntelliSense should be happy
4646

4747
As an example this spec includes 3rd party module [cypress-wait-until](https://github.com/NoriSte/cypress-wait-until). This module ships with its own TypeScript definition, which allows `cy.waitUntil` to work.
4848

49+
## Async commands
50+
51+
A custom command can call an async function from the application, the resolved value will be automatically yielded to the next command or assertion in the test. See [cypress/integration/async-command.js](cypress/integration/async-command.js) file.
52+
4953
## More info
5054

5155
- [Cypress custom commands](https://on.cypress.io/custom-commands)
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/// <reference types="cypress" />
2+
Cypress.Commands.add('asyncAdd', (a, b) => {
3+
cy.log(`${a} + ${b}`)
4+
// our application in "index.html" has placed a promise-returning
5+
// method "asyncAdd" onto the "window" object.
6+
// from the tests's custom command we can invoke that method
7+
// Cypress automatically waits for the promises to resolve
8+
// before yielding their value to the next command in the test
9+
// https://on.cypress.io/invoke
10+
cy.window().invoke('asyncAdd', a, b)
11+
})
12+
13+
describe('example', () => {
14+
it('adds numbers using custom command', () => {
15+
cy.visit('index.html')
16+
// the custom command will yield resolved value
17+
cy.asyncAdd(2, 3).should('equal', 5)
18+
})
19+
})

examples/fundamentals__add-custom-command/index.html

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,15 @@ <h1 data-cy="greeting">Page title</h1>
1212
document.body.appendChild(el)
1313
}, 1000)
1414
</script>
15+
16+
<script>
17+
// method is added to the "window" object dynamically
18+
setTimeout(() => {
19+
window.asyncAdd = (a, b) => {
20+
return new Promise((resolve) => {
21+
setTimeout(() => resolve(a + b), 1000)
22+
})
23+
}
24+
}, 1000)
25+
</script>
1526
</body>

0 commit comments

Comments
 (0)