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

标签 reactjs unit-testing jestjs material-ui enzyme

我正在尝试为我的 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/

相关文章:

reactjs - 无法解析 'os' ,webpack 5

reactjs - React-Select 搜索输入-土耳其语小写 "i"字符不起作用获取以 "İ"开头的结果(单词)

java - 模拟对象和接口(interface)

node.js - Jest 模拟和测试 require.resolve 调用

javascript - 如何使用浅层渲染测试装饰后的 React 组件

javascript - 从 React 组件返回 RSS

javascript - 动态添加/删除表单输入

c# - DDD 中的应用层单元测试是什么样的?

java - Apache DefaultHttpClient 调用结果为 "java.lang.RuntimeException: Stub!"

javascript - 使用 react 测试库测试到达路由器