gpt4 book ai didi

reactjs - 如何模拟和测试 MaterialUI - makeStyles

转载 作者:行者123 更新时间:2023-12-04 08:39:36 25 4
gpt4 key购买 nike

我正在尝试为我的 React 组件添加更好的测试覆盖率,而我无法模拟的地方之一就是这个内部

export const useTabStyles = makeStyles(({ options: { common } }) => ({
>>> root: ({ size }: TabProps) => ({
'&&': {
fontSize: size === 'MD' ? common.fonts.sizes.p3 : common.fonts.sizes.p,
},
}),
}));
当我检查代码覆盖率时,是说 >>>线路没有被检查。
我试过有这样的东西
jest.mock('@material-ui/core/styles', () => ({
...jest.requireActual('@material-ui/core/styles'),
makeStyles: jest.fn().mockReturnValue(jest.fn()),
}));
但后来我不确定,如何检查给定的行是否用 size = MD or LG 调用.
这是 it 的代码
it('should render normal style', () => {
wrapper = shallow(<Tab size="MD" />);
// how do I mock check here whtehr the makeStyles received the proepr size.
});

最佳答案

覆盖方面发生的事情是正在测试的函数,钩子(Hook) useTabStylesmakeStyles 的结果fn,它接受一个回调作为输入,这是缺少覆盖范围的回调,因为它没有在您的模拟之后执行。
如果您以这种方式更改您的模拟,这也应该执行将覆盖的代码:

makeStyles: jest.fn().mockImplementation(callback => {
callback({ options: { common: { fonts: { sizes: {} } } } }); // this will execute the fn passed in which is missing the coverage
return jest.fn().mockReturnValue({ // here the expected MUI styles });
}),
无论如何,您也可以忽略该 fn 的覆盖检查,只需在以下行之前添加:
/* istanbul ignore next */
export const useTabStyles = makeStyles(({ options: { common } }) => ({
root: ({ size }: TabProps) => ({
'&&': {
fontSize: size === 'MD' ? common.fonts.sizes.p3 : common.fonts.sizes.p,
},
}),
}));

关于reactjs - 如何模拟和测试 MaterialUI - makeStyles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64628908/

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