1

Trying to test my code that uses Notification API.

I don't think I'm mocking it correctly.

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
  });

This works.

But the following doesn't..

  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
  });
});
Lin Du
  • 88,126
  • 95
  • 281
  • 483
IamMowgoud
  • 308
  • 4
  • 13

1 Answers1

0

You should mock the Notification class and its static members.

Notification.permission is a static property and Notification.requestPermission() is a static method.

E.g.

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);
  });
});

test result:

 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
Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • This is working well and passing except for me the console.log is not logging. The mocked implementation doesn't get called. – IamMowgoud Mar 15 '21 at 19:18