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

问题描述

尝试测试我使用 Notification 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
  });
});

解决方法

您应该模拟 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