Tuesday, 27 November 2018

Enzyme simulate click event which makes API calls not working

In one of my projects, React-Instagram-Clone-2.0, I've added a feature which enables users to add other users to favourites.

I have a test which simulates click event done on the button which makes a POST request and adds user to favs. But it's doesn't reach the server and the test always passes.

Here is the code.

Add-to-favourites.js

const AddToFavourites = ({ user, username }) => {

let add = e => {
  e.preventDefault()
  addToFavourites(user)   // util function
  new d('.af_btn').blur()
}

return (
  <div>
    <div className='recomm_teaser'>
      <span>Wanna add {username} to your favourites list.</span>
      <SecondaryButton
        label='Add'
        onClick={add}
      />
    </div>
  </div>
)
}

addToFavourites function

export const addToFavourites = async user => {
  let {
    data: { success, mssg }
  } = await post('/api/add-to-favourites', { user }) // POST request

  if (success) {
    insta_notify({
      to: user,
      type: 'favourites'
    })
  }

  console.log('Test debugging')  // Never logged
  // But I remove the request, The above message is logged out.
  Notify({ value: mssg })
  }

And my test file

describe('AddToFavourites Component', () => {

const comp = (
  <AddToFavourites
    user={7}
    username='ghalib'
  />
)

it('should match snapshot', () => {
  const tree = create(comp).toJSON()
  expect(tree).toMatchSnapshot()
})

it('should add user to favs when clicked', () => {
  const wrapper = mount(comp)

  wrapper.find('SecondaryButton').simulate(
    'click',
    { preventDefault() {} }
  )

  expect(true).toBe(true)
 })

})

Any solution?

Thnx in advance :)



from Enzyme simulate click event which makes API calls not working

No comments:

Post a Comment