how to re-render after getting axios response in jest test

一曲冷凌霜 提交于 2019-12-04 17:28:47

The problem is that jest does not wait for async calls, have a look at the docs here. So the way how can you solve this is to give jest the promise that axios.get returns. This will not work if you use something that just mocks the async call inside axios. You have to mock axios complete out of your test like this:

jest.mock('axios', ()=> ({get:jest.fn()}))

now when importing axios into your file it will get an object where the get function is just a spy. To implement the spy so it will return a promise that you can give to jest you have to import it into your test:

import {get} from axios

now in your test create a resolved promise

test('xyz', async() = > {
  const p = Promise.resolve({
    data: {
      "id_user": "1",
      "id_person": "1",
      "imageUrl": "",
      "email": "xyz@zyz.com",
      "name": "xyz xyz"
    }
  })
  get.mockImplementation(() => p)
  var ProfilePic2 = require('../../src/views/ProfilePic');
  const component = renderer.create(
    <ProfilePic/>
  );
  expect(component.state).toBeDefined();
  //tree.props.setProfile({})
  let tree = component.toJSON();
  await p
  expect(tree).toMatchSnapshot();
});

Btw. I'm not sure if react-test-renderer will call componentDidMount, maybe you have to switch to enzyme.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!