Skip to content

Latest commit

 

History

History
63 lines (47 loc) · 2.09 KB

File metadata and controls

63 lines (47 loc) · 2.09 KB

Testing browser notifications

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

Tests

Checking if the browser supports notifications

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.

Notification preferences

Enabled Cypress notifications

The rest of the tests stubs Notification constructor to avoid popups

Testing if the browser does not support notifications

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')
})

See also