【发布时间】:2018-08-20 21:15:30
【问题描述】:
我有一个使用 Axios 获取数据的 react 组件:
import React from "react";
import axios from "axios";
export default class Example extends React.Component {
constructor() {
super();
axios("http://localhost/data.json").then(response => {
this.setState({
data: response.data
});
});
}
render() {
return <ul>{this.data.map(item => <li>{item}</li>)}</ul>;
}
}
我正在尝试围绕这个组件编写一些基本测试。首先我只是想让组件渲染......
import React from "react";
import { shallow } from "enzyme";
import Example from "./example";
it.only("Renders", () => {
const wrapper = shallow(<Example />);
const li = wrapper.find("li");
expect(li.length).toBe(2); // there are two items in the data file
});
...但是我得到的第一件事是来自 axios 的网络错误。
我是测试新手,我知道我需要进行模拟等组件的测试,但我的印象是你仍然可以使用实时端点,尽管它不是最佳的。
有没有办法告诉 Jest 等到组件渲染完成后再进行断言?
任何建议将不胜感激!
【问题讨论】:
-
终于找到了我从 Axios 收到网络错误的原因 - 需要在 create-react-app 测试脚本中进行此设置才能将环境设置为节点...
"test": "react-scripts test --env=jsdom --testEnvironment=node"This is mentioned here
标签: javascript reactjs axios jestjs enzyme