gpt4 book ai didi

reactjs - 用 Jest mock snackbar

转载 作者:行者123 更新时间:2023-12-03 23:45:28 30 4
gpt4 key购买 nike

我尝试测试以下代码

import { useSnackbar, VariantType, WithSnackbarProps } from 'notistack';
import React from 'react';

interface IProps {
setUseSnackbarRef: (showSnackbar: WithSnackbarProps) => void;
}

const InnerSnackbarUtilsConfigurator: React.FC<IProps> = (props: IProps) => {
props.setUseSnackbarRef(useSnackbar());
return null;
};

let useSnackbarRef: WithSnackbarProps;
const setUseSnackbarRef = (useSnackbarRefProp: WithSnackbarProps) => {
useSnackbarRef = useSnackbarRefProp;
};

export const SnackbarUtilsConfigurator = () =>
<InnerSnackbarUtilsConfigurator setUseSnackbarRef={setUseSnackbarRef} />;

export default {
success(msg: string) {
this.toast(msg, 'success');
},
warning(msg: string) {
this.toast(msg, 'warning');
},
info(msg: string) {
this.toast(msg, 'info');
},
error(msg: string) {
this.toast(msg, 'error');
},
toast(msg: string, variant: VariantType = 'default') {
useSnackbarRef.enqueueSnackbar(msg, { variant });
},
};
如果我模拟完整的 notstack 对象
import React from "react";
import {render as testingRender} from '@testing-library/react';
import { SnackbarProvider} from 'notistack';
import SnackbarUtils,{SnackbarUtilsConfigurator} from './SnackbarUtils';

jest.mock('notistack');

beforeEach(() =>{

});

it('DownloadDialog renders correctly - open=true', async () => {
const component = await testingRender(<SnackbarProvider maxSnack={3}><SnackbarUtilsConfigurator /></SnackbarProvider>);
SnackbarUtils.success("success");
});
我收到一条错误消息:
类型错误:无法读取未定义的属性“enqueueSnackbar”
  33 |   },
34 | toast(msg: string, variant: VariantType = 'default') {
> 35 | useSnackbarRef.enqueueSnackbar(msg, { variant });
| ^
36 | },
37 | };
因为 useSnackbarRef .
我怎么能只模拟 useSnackbar notitstack的方法,这样我就可以检查是否 enqueueSnackbar用正确的值调用?

最佳答案

这对我有用。将它放在所有测试之外(顶级范围):

const mockEnqueue = jest.fn();

jest.mock('notistack', () => ({
...jest.requireActual('notistack'),
useSnackbar: () => {
return {
enqueueSnackbar: mockEnqueue
};
}
}));

关于reactjs - 用 Jest mock snackbar ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63038665/

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