gpt4 book ai didi

reactjs - 如何模拟 Material-ui withStyles 的实现?

转载 作者:行者123 更新时间:2023-12-02 10:16:26 25 4
gpt4 key购买 nike

如何在 material-ui/core/styles.js 中模拟 withStyles 的实现?

这是测试:

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
)
)

但这不是测试的本地内容。

最佳答案

我发现解决这个问题的方法是按如下方式导出组件。无需模拟。

测试:

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)

关于reactjs - 如何模拟 Material-ui withStyles 的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51160904/

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