如何用HOC写出正确的开玩笑测试?

时间:2018-01-30 06:24:12

标签: javascript reactjs enzyme jest higher-order-components

我试图理解为什么我的开胃菜/酶测试失败了。我有一个组件,我使用redux in中的compose函数,结构如下:

class MyComponent extends Component {
    //code here
}

export default compose(
    connect(mapStateToProps),
)(MyComponent)

在我的开玩笑测试中,我这样做:

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

然而,我收到错误,例如&#34;无法读取属性&#39;状态&#39;未定义&#34;。我知道使用浅层渲染并不能给我我需要的确切结构,但我不确定还有什么可以尝试获得正确的结构。我尝试浅层渲染包装的组件,然后在其中找到未包装的组件,如component = shallow(<MyComponent {...props} />).find('MyComponent').shallow();,没有运气。任何其他建议将不胜感激。 `

1 个答案:

答案 0 :(得分:2)

通常您要测试组件而不是组件与redux的集成:

class MyComponent extends Component {
    //code here
}

export { MyComponent } // export the component
export default compose(
    connect(mapStateToProps),
)(MyComponent)

同样在您的测试中,您将导入指定的导出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);
  }
}

如果要测试与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>);
      }

你绝对应该是read the testing section的redux文档