【问题标题】:how to re-render after getting axios response in jest test在开玩笑测试中获得 axios 响应后如何重新渲染
【发布时间】:2017-09-28 02:59:23
【问题描述】:

我的组件:

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)
    });
}

我的测试:

//@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();
});

问题是 jest 正在测试初始渲染,而我需要在收到 API 响应后对其进行测试。因此,它所比较的​​快照也大多是空的。

我无法让测试等到第二次渲染之后。 我只是在尝试等待/异步,但无法让它工作。 我可以看到我的 api mocs 是从控制台日志中调用的。

【问题讨论】:

  • 使用 enzime 时,挂载的组件有一个 update() 方法,在我更改存储状态后我调用它,也许你可以使用类似的东西?
  • 你能从单位改变状态吗?如果可能的话,这可以部分解决我的问题。然后我将分别测试我的模拟 api 调用和我的渲染(使用给定的状态)。
  • 有一个简单的方法可以做到这一点。 browse-tutorials.com/snippet/…

标签: unit-testing reactjs jestjs axios


【解决方案1】:

问题在于 jest 不等待异步调用,请查看文档 here。因此,如何解决这个问题的方法是给开玩笑的承诺 axios.get 返回。如果您使用的只是模拟 axios 中的异步调用,这将不起作用。你必须像这样模拟 axios 完成你的测试:

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

现在当将axios 导入文件时,它会得到一个对象,其中get 函数只是一个间谍。要实现 spy,它会返回一个你可以给 jest 的承诺,你必须将它导入到你的测试中:

import {get} from axios

现在在您的测试中创建一个已解决的承诺

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();
});

顺便说一句。我不确定react-test-renderer 是否会打电话给componentDidMount,也许你必须改用酶。

【讨论】:

  • 没有用。严重错误被称为“错误:警告:setState(...):您传递了一个未定义或空状态对象;”
  • 更改为:const p = Promise.resolve({"data": {"id_user": "1", "id_person": "1", "imageUrl": "", "email" : "xyz@zyz.com", "name": "xyz xyz"}}) 然后让它工作。 :)
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 2019-08-31
  • 1970-01-01
  • 2019-10-08
  • 2020-08-16
  • 2020-10-23
  • 1970-01-01
  • 2018-08-05
相关资源
最近更新 更多