【问题标题】:How to mock Notifications API with JEST?如何使用 JEST 模拟通知 API?
【发布时间】:2020-08-15 00:05:45
【问题描述】:

我开玩笑地测试了 redux-actions。 特定的 redux-action 使用 Notifications API 作为副作用。如何模拟通知 API?

现在,我只是这样模拟它:

global.Notification = {...};

它有效,但我认为有更优雅的解决方案来解决这个问题。有什么想法吗?

我有这个模块来处理通知 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);
  }
}

【问题讨论】:

  • 恐怕没有办法。你能做的最好的是将模拟代码封装在单独的文件中,以避免在测试之间重复。
  • 你期望什么?你的单元测试有错误吗?

标签: api notifications mocking jestjs browser-api


【解决方案1】:

防止在每个测试文件中模拟 Notification API 的一种方法是配置 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>;

注意:globalThis 是访问全局范围的最现代方式。如果您没有所需的 Node 版本 (v12+),请坚持使用 global 对象。

这个例子也展示了 Typescript 的使用,这有点棘手。

如果你想模拟不同的权限状态,你可以在测试用例中这样做:

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


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

【讨论】:

  • spyOn 逻辑给出Cannot spyOn on a primitive value; undefined given 错误
  • @IamMowgoud 你在使用任何 JS 框架吗?在您的情况下,Jest 环境中似乎缺少 Notification API。根据您的设置(如herehere),您可以预期每个浏览器 的API 略有不同,但对于Jest 环境而言,AFAIK 并非如此。
猜你喜欢
  • 2022-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 2020-07-25
  • 2018-01-26
  • 2019-11-29
  • 2019-01-23
相关资源
最近更新 更多