我对测试还很陌生,所以也许我正在考虑测试不应该测试的东西。
我有一个顶级组件“App”,它从商店获取它的状态,它通过组件安装上的 ajax 请求更新。我认为一个有用的测试是在发出 ajax 请求(一个 Action )后检查 App 组件的状态是否为空。有没有办法在 Action 前后测试组件的状态?
据我了解,您不会测试应用程序的实际功能,而是模拟组件及其功能,然后对其进行测试。如果可行,您就认为您的实际应用程序一定能正常工作。我不确定如何模拟链接到操作和商店的组件。
如果我不应该测试状态,那么测试组件有什么好处?目前还没有任何用户交互。
这是没有存储/操作代码的组件代码:
import React from 'react';
import {Component} from 'react';
import {FETCH_DATA} from '../actions/types';
import MapStore from '../stores/MapStore';
import dispatcher from '../dispatcher';
import * as MapActions from '../actions/index';
export default class App extends Component {
constructor() {
super();
this.state = {
meteorites: MapStore.getAll()
}
// Bind methods to 'App'
this.updateData = this.updateData.bind(this);
}
componentWillMount() {
// fetch initial meteorites on page load
this.fetchData();
// if change event was emitted, re-render component
MapStore.on('change', this.updateData);
}
fetchData() {
// Kick off a fetchData action (api request)
MapActions.fetchData();
}
componentWillUnmount() {
MapStore.removeListener('change', this.updateData);
}
updateData() {
this.setState({
meteorites: MapStore.getAll()
});
}
render() {
//console.log("state", this.state.meteorites);
return (
<div className="app-container">Meteorite Landings</div>
);
}
}
最佳答案
如果您想了解有关深入测试的更多信息,我推荐 "Growing Object-Oriented Software, Guided by Tests"
特别与 React/Redux 相关,Redux 文档有一些关于测试 Redux 的信息:
http://redux.js.org/docs/recipes/WritingTests.html
对于其他面向 React 的测试,您可以查看 Enzyme和 Jest
另见
关于ajax - 如何测试 React/Flux 组件状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36657154/