测试期间未为子样式组件提供正确的主题
Child styled-component not being provided with correct theme during test
我正在尝试编写 mount(<MyComponent />)
但我在使用 MyComponent
呈现的 styled-components
时遇到了问题
子组件
const Layout = styled.View`
background-color: ${({ theme }) => theme.background.main};
`
测试组件
const MyComponent = () => (
<Modal visible>
<Layout>
...
</Layout>
</Modal>
)
我的测试
const theme = {
background: {
main: '#fff',
},
}
it ('should mount', () => {
mount(
<ThemeProvider theme={theme}>
<MyComponent />
</ThemeProvider>
)
})
当我运行这个测试时我得到一个错误Cannot read property 'main' of undefined
我尝试从 Layout
组件控制台记录 theme
道具,它确认提供的主题道具是一个空对象,而不是主题提供者的主题。有什么方法可以 mount
使用提供的主题吗?
我也尝试使用组件包装器,但结果保持不变
mount(<MyComponent />, {
wrappingComponent: ThemeProvider,
wrappingComponentProps: {
theme,
},
})
包版本:styled-components
是 4.3.2,enzyme
是 3.10.0
您的代码有一点错误。查看测试中的 theme
对象。
它有 属性 backgroundColor
但在您的代码中您使用 属性 theme.background
最终我能够使用 react-test-renderer
而不是 enzyme
让这个测试工作
辅助函数
const renderWithTheme = (component: JSX.Element) =>
renderer.create(<ThemeProvider theme={darkTheme}>{component}</ThemeProvider>)
测试:
it('renders', () => {
const component = renderWithTheme(
<InputModal open={true} value={'abc'} onEditing={mockEditing} title="Test" onEndEditing={mockEndEditing} />,
)
expect(component).toMatchSnapshot()
})
我正在尝试编写 mount(<MyComponent />)
但我在使用 MyComponent
styled-components
时遇到了问题
子组件
const Layout = styled.View`
background-color: ${({ theme }) => theme.background.main};
`
测试组件
const MyComponent = () => (
<Modal visible>
<Layout>
...
</Layout>
</Modal>
)
我的测试
const theme = {
background: {
main: '#fff',
},
}
it ('should mount', () => {
mount(
<ThemeProvider theme={theme}>
<MyComponent />
</ThemeProvider>
)
})
当我运行这个测试时我得到一个错误Cannot read property 'main' of undefined
我尝试从 Layout
组件控制台记录 theme
道具,它确认提供的主题道具是一个空对象,而不是主题提供者的主题。有什么方法可以 mount
使用提供的主题吗?
我也尝试使用组件包装器,但结果保持不变
mount(<MyComponent />, {
wrappingComponent: ThemeProvider,
wrappingComponentProps: {
theme,
},
})
包版本:styled-components
是 4.3.2,enzyme
是 3.10.0
您的代码有一点错误。查看测试中的 theme
对象。
它有 属性 backgroundColor
但在您的代码中您使用 属性 theme.background
最终我能够使用 react-test-renderer
而不是 enzyme
辅助函数
const renderWithTheme = (component: JSX.Element) =>
renderer.create(<ThemeProvider theme={darkTheme}>{component}</ThemeProvider>)
测试:
it('renders', () => {
const component = renderWithTheme(
<InputModal open={true} value={'abc'} onEditing={mockEditing} title="Test" onEndEditing={mockEndEditing} />,
)
expect(component).toMatchSnapshot()
})