我的setupTests.ts中有以下内容:
globalThis.Notification = ({
requestPermission: jest.fn(),
permission: "granted",
} as unknown) as jest.Mocked<typeof Notification>然而,在一个react项目中的jest测试中,我不断地得到这个错误:
TypeError: Notification is not a constructor
21 | export function showNotification(title: string, notificationText: string) {
22 | if (Notification.permission === "granted") {
> 23 | const notification = new Notification(title, { // params});如何正确地修复它以模拟Notification?
发布于 2022-08-05 21:37:44
我也面临着一个类似的问题。我使用下面的方法来模拟通知。Visual代码一直抱怨我模仿对象的方式,但是测试仍然运行得很完美。
我能够为close添加一个模拟函数,以后可以使用expect进行测试。
const mockClose = jest.fn();
global.Notification = jest.fn().mockImplementation(
() =>
(({
close: mockClose,
} as unknown) as Notification)
);
functionInCode(data); <--- Calls new Notification
expect(global.Notification).toBeCalledTimes(1);
expect(mockClose).toBeCalledTimes(1);https://stackoverflow.com/questions/73212911
复制相似问题