【发布时间】:2018-03-30 14:55:42
【问题描述】:
我是 react 和任何 javascript 测试框架的新手。
我有一个简单的组件,它从 API 中检索项目并将它们显示到屏幕上。
从componentWillMount调用函数getItems()。
是否可以等到 getItems() 完成后再进行断言?
ItemDetails.js
class ItemDetails extends Component {
constructor(props) {
super(props);
this.state = {
details: ''
}
}
componentWillMount() {
this.getItem();
}
getItem() {
const itemId = this.props.match.params.id;
fetch(`/api/items/${itemId}`)
.then(res => res.json())
.then(details => this.setState({ details }));
}
render() {
const details = this.state.details;
return (
<div>
<h1>{details.title}</h1>
...
</div>
);
}
}
export default ItemDetails;
ItemDetails.test.js
describe('ItemDetails', () => {
it('should render a div with title', () => {
const details = {
_id: 1,
title: 'ItemName'
};
fetch.mockResponseOnce(JSON.stringify(details));
const wrapper = mount(<ItemDetails match={{ params: {id: 1} }} />);
expect(wrapper.find('div').find('h1').text()).toBe('ItemName');
});
});
【问题讨论】:
标签: reactjs fetch enzyme jestjs