【问题标题】:Is there a way to Jest test and spy on Web Notification API?有没有办法对 Web Notification API 进行 Jest 测试和监视?
【发布时间】: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
  });
});

【问题讨论】:

    标签: javascript typescript jestjs web-notifications


    【解决方案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 没有记录。模拟的实现不会被调用。
    猜你喜欢
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 2010-11-13
    • 2021-07-20
    • 2011-03-23
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多