[英]How to write proper jest tests with HOC?
I'm trying to understand why my jest/enzyme tests are failing. 我试图理解为什么我的开胃菜/酶测试失败了。 I have a component that I use the
compose
function from redux in, structured as following: 我有一个组件,我使用redux的
compose
函数,结构如下:
class MyComponent extends Component {
//code here
}
export default compose(
connect(mapStateToProps),
)(MyComponent)
In my jest test, I do this: 在我的开玩笑测试中,我这样做:
Import { MyComponent } from ‘app/MyComponent’;
describe(‘<MyComponent />’, () => {
let component;
beforeEach(() => {
props = {
id: ‘23423’
}
component = shallow(<MyComponent {…props} />);
}
it(‘Loads correctly’, () => {
expect(component.state(‘isLoading’)).toEqual(true);
expect(component.find(‘InnerComponent’).length).toBe(1);
}
However, I get errors like "Cannot read property 'state' of undefined". 但是,我收到的错误如“无法读取未定义的属性'状态”。 I understand that using shallow rendering doesn't give me the exact structure that I need, but I'm not sure what else to try to get the right structure.
我知道使用浅渲染并不能给我我需要的确切结构,但我不确定还有什么可以尝试获得正确的结构。 I tried shallow-rendering the wrapped component and then finding the unwrapped component within it, like so,
component = shallow(<MyComponent {...props} />).find('MyComponent').shallow();
我尝试浅层渲染包装的组件,然后在其中找到未包装的组件,如下所示,
component = shallow(<MyComponent {...props} />).find('MyComponent').shallow();
, with no luck. ,没有运气。 Any other suggestions would be appreciated.
任何其他建议将不胜感激。 `
`
Usually you want to test the component and not the integration of the component with redux: 通常您要测试组件而不是组件与redux的集成:
class MyComponent extends Component {
//code here
}
export { MyComponent } // export the component
export default compose(
connect(mapStateToProps),
)(MyComponent)
Also on your test you would import the named export import { MyComponent } from '...'
instead of importing the default: import MyComponent from '..'
同样在测试中,您
import { MyComponent } from '...'
导入命名导出import { MyComponent } from '...'
而不是导入默认值: import MyComponent from '..'
import { MyComponent } from ‘app/MyComponent’;
describe(‘<MyComponent />’, () => {
let component;
beforeEach(() => {
props = {
id: ‘23423’
}
component = shallow(<MyComponent {…props} />);
}
it(‘Loads correctly’, () => {
expect(component.state(‘isLoading’)).toEqual(true);
expect(component.find(‘InnerComponent’).length).toBe(1);
}
}
If you want to test component interactions with your redux store you need to wrap your component with a <Provider />
如果要测试与redux存储的组件交互,则需要使用
<Provider />
包装组件
import { MyComponent } from ‘app/MyComponent’;
import { Provider } from 'react-redux'
describe(‘<MyComponent />’, () => {
let component;
beforeEach(() => {
props = {
id: ‘23423’
}
component = shallow(<Provider><MyComponent {…props} /></Provider>);
}
You should definitely read the testing section of the redux documentation 您一定要阅读 redux文档的测试部分
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.