大佬教程收集整理的这篇文章主要介绍了有没有办法 Jest 测试和监视 Web Notification API?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试测试我使用 Notification API 的代码。
我认为我没有正确地嘲笑它。
@H_404_4@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
});
这有效。
但以下没有..
@H_404_4@ 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 @R_183_10586@l
Tests: 2 passed,2 @R_183_10586@l
Snapshots: 0 @R_183_10586@l
Time: 4.284 s
以上是大佬教程为你收集整理的有没有办法 Jest 测试和监视 Web Notification API?全部内容,希望文章能够帮你解决有没有办法 Jest 测试和监视 Web Notification API?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。