Con*_*ine 5 api notifications mocking jestjs browser-api
我开玩笑地测试 redux-actions。特定的 redux-action 使用 Notifications API 作为副作用。我如何模拟通知 API?
现在,我只是这样嘲笑它:
global.Notification = {...};
Run Code Online (Sandbox Code Playgroud)
它有效,但我认为有更优雅的解决方案来解决这个问题。有任何想法吗?
我有这个模块来处理通知 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);
}
}
Run Code Online (Sandbox Code Playgroud)
防止在每个测试文件中模拟通知 API 的一种方法是配置 Jest setupFiles。
笑话配置.js
module.exports = {
setupFiles: ["<rootDir>config.ts"],
};
Run Code Online (Sandbox Code Playgroud)
配置.ts
globalThis.Notification = ({
requestPermission: jest.fn(),
permission: "granted",
} as unknown) as jest.Mocked<typeof Notification>;
Run Code Online (Sandbox Code Playgroud)
注意: globalThis是访问全局范围的最现代的方式。如果您没有所需的 Node 版本 ( v12+ ),请继续使用globalobject。
此示例还展示了Typescript的使用,这有点棘手。
如果你想模拟不同的权限状态,你可以在测试用例中这样做:
// Notification.permission
jest
.spyOn(window.Notification, "permission", "get")
.mockReturnValue("denied");
// Notification.requestPermission (which is a Promise)
jest
.spyOn(window.Notification, "requestPermission")
.mockResolvedValueOnce("granted");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1432 次 |
| 最近记录: |