Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 139863

Testing asynchronous componentDidMount that changes state with Jest and Enzyme

$
0
0

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 run 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 solely for testing out Jest with Enzyme. How can I test this component correctly?


Viewing all articles
Browse latest Browse all 139863

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>