I am making a call to an internal server to give me back whatever data, and in order to mock this i am using axios-mock-adapter and sending back an array with 5 things. I have to mount component twice to make this test pass. here is my component:
import React, { Component, Fragment } from 'react'
import axios from 'axios'
export default class HelloWorld extends Component {
constructor(props) {
super(props)
this.state = {
goodbye: false,
data: []
}
}
async componentDidMount() {
await this.func()
console.log("RUNNING");
}
func = async () => {
let data;
try {
data = await axios.get('http://localhost:8080');
}
catch(e) {
console.log("ERROR");
throw(e)
}
this.setState({data: data.data})
}
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 the test:
it('there is data being returned', async () => {
let mock = new MockAdapter(axios)
const data = new Array(5).fill('Hello World')
mock.onGet('http://localhost:8080').reply(200, data)
const component = await mount(<HelloWorld />)
//if this line below is commented out the test fails
await component.instance().componentDidMount();
expect(component.state('data')).toHaveLength(5)
})
not sure why i have to mount the component and then mount it again. Anyone have any ideas?