有没有办法对 Web Notification API 进行 Jest 测试和监视?

Posted

技术标签:

【中文标题】有没有办法对 Web Notification API 进行 Jest 测试和监视?【英文标题】:Is there a way to Jest test and spy on Web Notification API? 【发布时间】:2021-03-15 02:41:55 【问题描述】:

尝试测试我使用通知 API 的代码。

我认为我没有正确地嘲笑它。

global.Notification = (
      requestPermission: jest.fn().mockImplementation(()=> 
        console.log('reached here') //never logged
        return 'denied';
      ),
      permission: 'denied',
     as unknown) as jest.Mocked<typeof Notification>;
    
    


  test('should ask for permission from Notifications API ', async () => 
    expect(global.Notification.requestPermission).toBeCalledTimes(1); // WORKS although console.log above never worked
  );

这行得通。

但以下不是..

  test('should create a new notification ', async () => 

    // some code that eventually runs this
    new Notification("Test");

    expect(global.Notification).toBeCalledTimes(1); // TypeError: Notification is not a constructor
  );
);

【问题讨论】:

【参考方案1】:

您应该模拟 Notification 类及其静态成员。

Notification.permission 是静态属性,Notification.requestPermission() 是静态方法。

例如

describe('66631725', () => 
  const mNotification = jest.fn();
  Object.defineProperty(global, 'Notification', 
    value: mNotification,
  );

  const staticMembers = 
    requestPermission: jest.fn().mockImplementation(() => 
      console.log('reached here');
      return 'denied';
    ),
    permission: 'denied',
  ;

  Object.assign(global.Notification, staticMembers);

  test('should ask for permission from Notifications API ', () => 
    new Notification('Test');
    expect(Notification).toBeCalledTimes(1);
    expect(Notification.permission).toEqual('denied');
  );

  test('should request permission', () => 
    Notification.requestPermission();
    expect(Notification.requestPermission).toBeCalledTimes(1);
  );
);

测试结果:

 PASS  examples/66631725/index.test.ts
  66631725
    ✓ should ask for permission from Notifications API  (3 ms)
    ✓ should request permission (13 ms)

  console.log
    reached here

      at Function.<anonymous> (examples/66631725/index.test.ts:9:15)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.284 s

【讨论】:

这运行良好,除了我之外,console.log 没有记录。模拟的实现不会被调用。

以上是关于有没有办法对 Web Notification API 进行 Jest 测试和监视?的主要内容,如果未能解决你的问题,请参考以下文章

Python Notification Popup消失了

Web Notifications

Web/Desktop Notification API - 在刷新页面时强制关闭所有通知

有没有办法在不使用mod_rewrite和.htaccess的情况下重写我的网址?

每天进步一点----- Notification

自定义状态栏notification布局