gpt4 book ai didi

javascript - 模拟通知 API

转载 作者:行者123 更新时间:2023-11-30 06:51:09 25 4
gpt4 key购买 nike

我有这个代码:

const browserNotification = new Notification(title, options);

browserNotification.onshow = () => this.props.sendTracking('in-app-chat-notification-start');

browserNotification.onclick = event => {
const notification = event.target;

this.props.router.push(notification.data.url.split('.com')[1]);
this.props.sendTracking('in-app-chat-notification-complete');

notification.close();
};

我正在尝试模拟窗口通知,因为我需要调用这两个方法(onshowonclick):

it('should call onshow method', () => {
window.Notification = () => ({
onshow: jest.fn(),
onclick: jest.fn()
});
const instance = shallow(<MyComponent />).instance();

instance.myMethod();

//window.Notification.onShow();

expect(sendTracking).toHaveBeenCalledTimes(1);
});

我知道如果这样做,我将失去原来的方法,但由于测试没有窗口和通知,我必须模拟它。

如何正确使用 Jest 来传递此代码?

我也试过用 global 进行模拟, 但最后与 window.

覆盖范围:

enter image description here

谢谢

最佳答案

最后,我通过拆分问题中显示的代码成功地测试了这两种方法。

就是这样:

handleNewFirebaseNotification = notification => {
const title = notification.data.title || 'letgo';
const options = {
body: notification.data.body,
icon: notification.data.icon || 'https://static.letgo.com/site-images/logo_letgo_share_fb.jpg',
data: {
url: notification.data.url
}
};

this.handleNotifications(title, options);
};

handleNotifications = (title, options) => {
const browserNotification = new Notification(title, options);

browserNotification.onshow = this.onShowNotification;
browserNotification.onClick = this.onClickNotification;
}

onShowNotification = () => {
this.props.sendTracking('in-app-chat-notification-start')
}

onClickNotification = event => {
const notification = event.target;

this.props.router.push(notification.data.url.split('.com')[1]);
this.props.sendTracking('in-app-chat-notification-complete');

notification.close();
}

然后我可以用 enzyme 测试所有这些新方法。例如:

it('should call handleNewFirebaseNotification and then call handleNotifications with title and icon', () => {
window.Notification = () => ({
onshow: jest.fn(),
onclick: jest.fn()
});
const instance = shallow(mockComponent()).instance();
const notificationMock = {
data: {
title: 'test',
body: 'test',
icon: 'test',
url: 'test'
}
};

instance.handleNewFirebaseNotification(notificationMock);

expect(window.Notification()).toEqual(expect.objectContaining({
onshow: expect.any(Function),
onclick: expect.any(Function)
}));
});

还有其中一种新方法:

it('should call onShowNotification', () => {
const instance = shallow(mockComponent()).instance();

instance.onShowNotification();

expect(sendTrackingSpy).toHaveBeenCalledTimes(1);
});

关于javascript - 模拟通知 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47226913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com