gpt4 book ai didi

unit-testing - 在 Jest 测试中获得 axios 响应后如何重新渲染

转载 作者:行者123 更新时间:2023-12-01 13:23:43 25 4
gpt4 key购买 nike

我的组件:

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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4dcdddee4deddde8ac7cbc9" rel="noreferrer noopener nofollow">[email protected]</a>",
"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 是从控制台日志中调用的。

最佳答案

问题是 jest 不等待异步调用,请查看文档 here 。因此,解决这个问题的方法是给 jest 提供 axios.get 返回的 promise 。如果您使用只是模拟 axios 内的异步调用的东西,这将不起作用。您必须像这样模拟 axios 完成测试:

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

现在,当将 axios 导入到您的文件中时,它将获得一个对象,其中 get 函数只是一个 spy 。要实现 spy ,使其返回一个可对于Jest的 promise ,您必须将其导入到您的测试中:

import {get} from axios

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

test('xyz', async() = > {
const p = Promise.resolve({
data: {
"id_user": "1",
"id_person": "1",
"imageUrl": "",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7dfdedde7dddedd89c4c8ca" rel="noreferrer noopener nofollow">[email protected]</a>",
"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,也许你必须切换到 enzyme 。

关于unit-testing - 在 Jest 测试中获得 axios 响应后如何重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com