jeudi 31 janvier 2019

I cannot test asynchronous componentDidMount that changes state with jest and enzyme

All I am doing in my code is upon componentDidMount being run, I am making an axios get request to Github, and setting some data back onto state, however when I am running the test it still says the state is an empty array, here is my component below:

export default class HelloWorld extends Component {
constructor(props) {
    super(props)
    this.state = {
        goodbye: false,
        data: []
    }

}

async componentDidMount() {
    await this.func()
}

func = async () => {
    let data = await axios.get('https://api.github.com/gists')
    this.setState({data: data.data})
    console.log(this.state)
}

goodbye = () => {
    this.setState((state, currentProps) => ({...state, goodbye: !state.goodbye}))
}

render() {
    return (
        <Fragment>
            <h1>
                Hello World
            </h1>
            <button id="test-button" onClick={this.goodbye}>Say Goodbye</button>
            {
                !this.state.goodbye ? null :
                <h1 className="goodbye">GOODBYE WORLD</h1>
            }
        </Fragment>
    )
}

}

and here is my test:

it('there is data being returned', async () => { 
    const component =  await mount(<HelloWorld />)       

    component.update()

    expect(component.state('data')).toHaveLength(30)

})

I am very new to using jest and am not sure what I am doing wrong, this app was built soley for testing out jest with enzyme. please let me know if I am doing something wrong!

Aucun commentaire:

Enregistrer un commentaire