我有这个代码:
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();
};
我正在尝试模拟窗口通知,因为我需要调用这两个方法(onshow 和 onclick):
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.
覆盖范围:
谢谢
最佳答案
最后,我通过拆分问题中显示的代码成功地测试了这两种方法。
就是这样:
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/