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

感情迁移 提交于 2020-01-13 06:30:48

问题


My component:

componentDidMount() {
    // Make HTTP reques with Axios
    axios.get(APIConfig.api_profile()).then((res) => {
        // Set state with result
        this.setState(res.data);
        console.log('I was triggered during componentDidMount')
        console.log(res)
    });
}

And my test:

//@see https://github.com/ctimmerm/axios-mock-adapter
mock.onGet(APIConfig.api_profile()).reply(200, {
    "id_user": "1",
    "id_person": "1",
    "imageUrl": "",
    "email": "xyz@zyz.com",
    "name": "xyz xyz"
});

test('xyz', async() => {

    var ProfilePic2 =require('../../src/views/ProfilePic');
    const component = renderer.create(
        <ProfilePic/>
    );

    expect(component.state).toBeDefined();
    //tree.props.setProfile({})
    let tree = component.toJSON();
    await expect(tree).toMatchSnapshot();
});

The problem is that jest is testing on initial render while I need to test it after a API response is received. Therefore the snapshot that it is comparing to is also mostly empty.

I am not able make the test wait till after the second render. I am just trying await/async but cannot get it to work. I can see my api mocs was called from the console log.


回答1:


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.



来源:https://stackoverflow.com/questions/43706501/how-to-re-render-after-getting-axios-response-in-jest-test

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