代码之家  ›  专栏  ›  技术社区  ›  David

如何用样式模拟Material UI的实现?

  •  1
  • David  · 技术社区  · 7 年前

    如何模拟 withStyles 在里面 material-ui/core/styles.js ?

    以下是测试:

    import React from 'react'
    import { shallow } from 'enzyme'
    import { withStyles } from '@material-ui/core/styles'
    
    import TempComponent from './TempComponent'
    
    jest.mock('@material-ui/core')
    
    it('renders correctly', () => {
      const withStylesFake = styles =>
        component => (
          component
        )
    
      withStyles.mockImplementation(withStylesFake)
    
      const wrapper = shallow(<TempComponent />)
      expect(wrapper).toMatchSnapshot()
    })
    

    代码如下:

    import React from 'react'
    import { withStyles } from '@material-ui/core/styles'
    
    const TempComponent = () => (
      <button>Click Me!</button>
    )
    
    export default withStyles({})(TempComponent)
    

    错误如下:

    TypeError: _styles.withStyles.mockImplementation is not a function
    
      at Object.<anonymous>.it (src/TempComponent.snapshot.test.js:15:22)
          at new Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)
    

    这是可行的:

    // ./__mocks__/@material-ui/core/styles
    export const withStyles = styles => (
      component => (
        component
      )
    ) 
    

    但这并不是测试的地方。

    3 回复  |  直到 6 年前
        1
  •  3
  •   David    7 年前

    import React from 'react'
    import { shallow } from 'enzyme'
    
    import { TempComponent } from './TempComponent'
    
    it('renders correctly', () => {
      const wrapper = shallow(<TempComponent />)
      expect(wrapper).toMatchSnapshot()
    })
    

    import React from 'react'
    import { withStyles } from '@material-ui/core/styles'
    
    export const TempComponent = () => (
      <button>Click Me!</button>
    )
    
    export default withStyles({})(TempComponent)
    
        2
  •  2
  •   stone    6 年前

    TempComponent

    jest.mock

    styles core withStyles

    jest.mock('@material-ui/core/styles', () => ({
      withStyles: styles => component => component
    }));
    

        3
  •  -1
  •   user2600410    6 年前

    import { withStyles } from '@material-ui/core/styles';
    
    const styles = theme => ({
      root: {
        ...theme.mixins.gutters(),
        paddingTop: theme.spacing.unit * 2,
        paddingBottom: theme.spacing.unit * 2,
        marginBottom: theme.spacing.unit * 3,
        maxWidth: theme.spacing.unit * 120,
        overflowX: 'auto',
      },
    });
    
    function PaperSheet() {
        return (
            <Paper className={classes.root} elevation={1} />
        );
    }
    
    export default withStyles(styles)(PaperSheet);
    
    推荐文章