Skip to content
This repository was archived by the owner on Dec 12, 2020. It is now read-only.

Commit 711c664

Browse files
committed
feat: spy on window.alert
1 parent c52a1c8 commit 711c664

File tree

4 files changed

+42
-0
lines changed

4 files changed

+42
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,10 @@ it('can display mock XHR response', () => {
501501
})
502502
```
503503

504+
### Spying on `window.alert`
505+
506+
Calls to `window.alert` are automatically recorded, but do not show up. Instead you can spy on them, see [AlertMessage.vue](components/AlertMessage.vue) and its test [cypress/integration/alert-spec.js](cypress/integration/alert-spec.js)
507+
504508
## Bundling
505509

506510
How do we load this Vue file into the testing code? Using webpack preprocessor.

components/AlertMessage.vue

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<template>
2+
<button @click="handleClick">Alert me</button>
3+
</template>
4+
5+
<script>
6+
export default {
7+
name: 'AlertMessage',
8+
methods: {
9+
handleClick() {
10+
alert('Hello Vue')
11+
}
12+
}
13+
}
14+
</script>

cypress/integration/alert-spec.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import AlertMessage from '../../components/AlertMessage.vue'
2+
const mountVue = require('../..')
3+
4+
/* eslint-env mocha */
5+
describe('AlertMessage', () => {
6+
beforeEach(mountVue(AlertMessage))
7+
it('loads', () => {
8+
cy.get('button').should('be.visible')
9+
})
10+
11+
it('calls window.alert', () => {
12+
const spy = cy.spy().as('alert')
13+
cy.on('window:alert', spy)
14+
cy.get('button').click()
15+
cy.get('@alert').should('have.been.calledOnce')
16+
cy.get('@alert').should('have.been.calledWith', 'Hello Vue')
17+
})
18+
})

src/index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,11 @@ function setXMLHttpRequest (w) {
136136
return w
137137
}
138138

139+
function setAlert (w) {
140+
window.alert = w.alert
141+
return w
142+
}
143+
139144
// the double function allows mounting a component quickly
140145
// beforeEach(mountVue(component, options))
141146
const mountVue = (component, optionsOrProps = {}) => () => {
@@ -158,6 +163,7 @@ const mountVue = (component, optionsOrProps = {}) => () => {
158163
return cy
159164
.window({ log: false })
160165
.then(setXMLHttpRequest)
166+
.then(setAlert)
161167
.its('Vue')
162168
.then(Vue => {
163169
installMixins(Vue, options)

0 commit comments

Comments
 (0)