mercredi 7 juin 2017

Get The State of Connected Components in Jest & Enzyme

Good day people! Let's say that i have this component Class:

@connect(
  state =>({
    someState: state.oneLevel.response
  })
)
export default class SomeClass extends React.Component{
constructor(props){
  super(props)
  this.state ={
    someState: [],
    isLoading: false,
    isLoaded: false
  }
}
}

This component has an async call with superagent

componentDidMount(){
 var url = 'http://ift.tt/2rXL0rV'
 this.setState({isLoading: true})
 request.get(url)
 .set('some headers 1', 'somevalue')
 .set('some headers 2', 'somevalue')
 .then((success) => {
      this.setState({
        isLoading: false,
        isLoaded: true
      })
 })
}

Now I've been assigned to write a unit test for this Component to check whether it has successfully changed its state or not. I'm using Jest as my test framework and enzyme for handling DOM Renderer etc.

describe("Network Functionality", ()=>{
  const wrapper = mount(<Provider store={store}><SomeComponent /><Provider>)
  
  it("Should change the isLoaded state to true", ()=>{
    const expectedState = true
    //mocking with supertest
    return mockApi().get('http://ift.tt/2sVJaFr')
    .set('some-headers1', 'somevalue')
    .set('some-headers2', 'somevalue')
    .then((success) => {
    expect(wrapper.state(isLoaded)).toEqual(expectedState)
    })
  }
})

With that code the response is as follows: TypeError: Cannot read property 'isLoaded' of null

my question is, is there anyway to get the state using connected components? I've tried exporting the component as ConnectedComponents and {Components} and it works flawlessly but I want to use connected components.

Why did I want to use connected components? Because the every components of my applications is built using this scheme and its not feasible to export as ConnectedComponents and {Components} for there is so many components within my applications and it might leads to more problems

Aucun commentaire:

Enregistrer un commentaire