mercredi 29 novembre 2017

Testing called function from within a fetch call

I am using jest and enzyme with jest-fetch-mock to try to write a test which asserts that a function is called from within a resolved fetch call, and I am not having much luck.

I have the following function:

function getHeadersClaims(){
  return fetch(headers, Object.assign({}, commonConfig, {method: 'GET'}))
}

I have a component that uses the function in componentWillMount:

componentWillMount() {
  getHeadersClaims()
    .then((res) => {
      return res.json()
    }).then((json) => {
      this.props.omniture(json)
    })
}

I am trying to test to see that this.props.omniture is called:

function generateProps() {
  return {
    omniture: jest.fn()
  }
}    

describe('Home', () => {
  beforeEach(function() {
    fetch.mockResponse(JSON.stringify([{}]))
  })

  it('should call componentWillMount()', () => {
    const props = generateProps()

    const spy = jest.spyOn(Home.prototype, "componentWillMount")
    const wrapper = shallow(<Home  {...props} />)
    expect(spy).toHaveBeenCalledTimes(1)
    expect(props.omniture).toHaveBeenCalled()
    // expect(wrapper.instance().props.omniture).toHaveBeenCalled() *also tried this*
  })
})

My test fails with:

expect(jest.fn()).toHaveBeenCalled()

My question is, how do I assert that this.props.omniture actually gets called. I have put in console log statements and it appears to get to the section of code where the call is made, but it is never called. Any help would be appreciated.

UPDATE:

It seems like jest is expecting the call to happen within the first then(). If I add the call there, the test passes. I also did some step-through debugging in VS Code and I do see that the call is being made.

Aucun commentaire:

Enregistrer un commentaire