Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Notifications API with JEST?

I test redux-actions with jest. Particular redux-action uses Notifications API as a side-effect. How can i mock Notifications API?

Now, i simply mock it this way:

global.Notification = {...};

It works, but i think there is more elegant solution to solve this problem. Any ideas?

I have this module to handle Notifications API:

export const requestNotifyPermission = () => {
    try {
        return Notification.requestPermission().then(function(result) {
            return result;
        });
    } catch(err) {
        console.warn('NotificationsAPI error: ' + err);
    }
};

export const getCurrentNotifyPermission = () => {
    // Possible values = default, granted, denied
    try {
      return Notification.permission;
    } catch {
      return 'denied';
    }
};

export const createNotify = (title, body)  => {
  try {
    if (getCurrentNotifyPermission() === 'granted') {
      var options = {
          body: body
      };
      return new Notification(title, options);  
    }
  } catch(err) {
    console.warn('NotificationsAPI error: ' + err);
  }
}
like image 949
Constantine Avatar asked Oct 27 '22 15:10

Constantine


1 Answers

One way to prevent mocking Notification API at every test file, is by configuring Jest setupFiles.

jest.config.js

module.exports = {
  setupFiles: ["<rootDir>config.ts"],
};

config.ts

globalThis.Notification = ({
  requestPermission: jest.fn(),
  permission: "granted",
} as unknown) as jest.Mocked<typeof Notification>;

Note: globalThis is the most modern way to access the Global scope. If you don't have the required Node version (v12+), just stick with using global object.

This example is also showcasing the use with Typescript, which is a little more tricky.

If you want to mock different permission states, you can do that in the test case:

// Notification.permission
jest
  .spyOn(window.Notification, "permission", "get")
  .mockReturnValue("denied");


// Notification.requestPermission (which is a Promise)
jest
  .spyOn(window.Notification, "requestPermission")
  .mockResolvedValueOnce("granted");

like image 149
Guilherme Maia Avatar answered Nov 09 '22 10:11

Guilherme Maia