【发布时间】: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