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);
}
}
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With