如何管理包含主题数据的组件的单元测试快照?
How to manage unit tests snapshots for components containing theme data?
让我们假设这个简单的例子有一个组件和一个单元测试
component.jsx
const theme = process.env.THEME
export const Component = ({ title }) => {
return (
<>
<h2>{theme} {title}</h2>
</>
)
}
component.test.jsx
import { Component } from './Component'
describe('<Component />', () => {
it('renders properly', () => {
const wrapper = shallow(<Context {...props} />)
expect(wrapper).toMatchSnapshot()
})
})
我正在 运行 的项目取决于 const 主题 ,所以在我的管道中我有更多的构建,更多的部署,每个主题一个。
当然,快照失败是因为每次我 运行 toMatchSnapshot() 功能时,它都会写入/检查文件夹 ./__snapshots__
中的输出,所以第一个主题 运行 的测试成功,然后其他主题的测试失败。
这个问题有解决办法吗?
- 为每个组件提供 主题 作为道具(糟糕的方法)
- 避免对这些组件使用快照(不是很好的方法,因为我想为我的测试套件保留此功能)
- 使用 React.createContext(好方法,但需要对整个项目进行一些重构)
我可以尝试使用更好的东西吗?
提前谢谢大家
React.createContext 使用模拟上下文数据进行测试确实是最好的方法。
让我们假设这个简单的例子有一个组件和一个单元测试
component.jsx
const theme = process.env.THEME
export const Component = ({ title }) => {
return (
<>
<h2>{theme} {title}</h2>
</>
)
}
component.test.jsx
import { Component } from './Component'
describe('<Component />', () => {
it('renders properly', () => {
const wrapper = shallow(<Context {...props} />)
expect(wrapper).toMatchSnapshot()
})
})
我正在 运行 的项目取决于 const 主题 ,所以在我的管道中我有更多的构建,更多的部署,每个主题一个。
当然,快照失败是因为每次我 运行 toMatchSnapshot() 功能时,它都会写入/检查文件夹 ./__snapshots__
中的输出,所以第一个主题 运行 的测试成功,然后其他主题的测试失败。
这个问题有解决办法吗?
- 为每个组件提供 主题 作为道具(糟糕的方法)
- 避免对这些组件使用快照(不是很好的方法,因为我想为我的测试套件保留此功能)
- 使用 React.createContext(好方法,但需要对整个项目进行一些重构)
我可以尝试使用更好的东西吗? 提前谢谢大家
React.createContext 使用模拟上下文数据进行测试确实是最好的方法。