我有一个我正在测试的连接组件。它根据状态呈现不同的元素。
安装时,它会获取要在表格中显示的数据。
class EventList extends Component {
componentDidMount() {
this.props.requestEvents();
}
render() {
return (
<div>
{renderWhat(this.props)}
</div>
);
}
}
requestEvents
操作会触发,但测试中不会发生任何调度。
行动:
requestEvents: () => async (dispatch, getState) => {
dispatch({ type: eventActions.requestEventsType });
const url = 'someurl';
const request = new Request(url, {
method: 'GET'
});
const response = await fetch(request)
if (response.status === 200) {
const events = response.json()
dispatch({ type: eventActions.receiveEventsType, events: events })
}
else if (response.status >= 400) {
dispatch({ type: statusCodeAction.unkown, error: "requestEvents", status: response.status })
}
}
reducer初始状态:
const initialState = {
events: [],
isLoading: false,
isCreating: false,
isEditing: false,
currentEvent : []
}
减速器:
if (action.type === eventActions.requestEventsType) {
return {
...state,
events: state.events,
isLoading: true
}
}
if (action.type === eventActions.receiveEventsType) {
return {
...state,
events: action.events,
isLoading: false
}
测试:
Enzyme.configure({ adapter: new Adapter() });
const middlewares = [thunk]
const mockStore = configureStore(middlewares)
describe('<EventList />', () => {
it('renders fetched events in a table', async () => {
fetchMock.reset();
fetchMock.restore();
const initialState = {
events: [{
id: 33,
description: "test",
startTime: "3/3/3",
endTime: "4/4/4"
}],
isLoading: false,
isCreatingFirstStep: false,
isEditing: false,
currentEvent: []
};
const reducers = {
errorStoreReducer: ErrorReducer.errorReducer,
eventStoreReducer: EventReducer.eventReducer,
form: reduxFormReducer
};
const store = mockStore({ ...reducers, ...initialState });
var mockList = JSON.stringify([
{
id: 15,
description: "mockList1",
startTime: "1/1/1",
endTime: "2/2/2"
},
{
id: 33,
description: "mockList2",
startTime: "3/3/3",
endTime: "4/4/4"
}
]);
var response = {
status: 200,
headers: {
'Content-Type': 'application/json'
},
body: mockList
};
fetchMock.mock('*', response);
const wrapper = mount(
<Provider store={store}>
<EventList />
</Provider>
);
});
});
通过控制台日志记录,我可以看到fetch被正确模拟并且包含正确的数据。 如果我控制台记录减速器(在任何条件检查之外)我可以看到它在任何动作被触发之前就开始了。
挂载的组件在操作完成之前呈现,因此在获取完成之前,除了initialState提供的数据之外,不会呈现任何数据。
如果我控制台登录减速机的条件,它们从不打印任何东西。
我可以做些什么来进行调度?