mercredi 7 février 2018

Test fetch method in React component using jest and enzyme doesn't update state of component

Trying to write a test for a react component using Jest and Enzyme. I'm trying to access a fetch method within the component but it wont update the state of the instance().

for this.state.dataLoaded(default value is false): Expected value to be (using ===): true Received: false

mockData.json is in the same folder as the test, and cleanData is the same as mockData.json

Test:

it('downloads the data', () => {
    const wrapper = mount(<Upload />)
    const instance = wrapper.instance()
    instance.readData('mockData.json')
    expect(instance.state.dataLoaded).toBe(true)
    expect(instance.state.data).toEqual(cleanData)
  })

fetch method inside of component:

readData(url) {
    fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then((response) => {
        return response.json()
      })
      .then((data) => {
        this.setState({
          dataLoaded: true,
          data: data,
        })
      })
      .catch((error) => {
        this.setState({
          dataLoaded: false,
          data: [],
          error: error,
        })
      })
  }

Aucun commentaire:

Enregistrer un commentaire