Read the blog post Testing the Browser Notification API.
You can find the sample app in index.html and all tests in cypress/e2e/spec.cy.js. The tests spy / stub Notification function in various ways to check how the app handles:
- permission was granted before
- permission was denied before
- permission was neither granted nor denied before, so the app asks the user and acts depending on the answer
The first test just checks that the browser supports notifications
it('are supported by the test browser', () => {
cy.visit('index.html')
cy.window().should('have.property', 'Notification').should('be.a', 'function')
})
If you enable notifications from Cypress itself, you will see a popup if you click "Notify me!" button.
The rest of the tests stubs Notification constructor to avoid popups
Application code
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
return
}
Test
it('shows alert if the browser does not support notifications', () => {
cy.visit('index.html', {
onBeforeLoad (win) {
delete win.Notification
},
})
cy.on('window:alert', cy.stub().as('alerted'))
cy.get('button').click()
cy.get('@alerted').should('have.been.calledOnce')
.and('have.been.calledWith', 'This browser does not support desktop notification')
})
- Cypress guide to Stubs, spies and clocks
- Read Mozilla Notification page
cy.stub
- Cypress Automation