【发布时间】:2017-07-28 19:47:49
【问题描述】:
我有一个中间件等待ARTICLE_REQUEST 操作,执行fetch 并在提取完成时分派ARTICLE_SUCCESS 或ARTICLE_FAILURE 操作。像这样
import { articleApiUrl, articleApiKey } from '../../environment.json';
import { ARTICLE_REQUEST, ARTICLE_SUCCESS, ARTICLE_FAILURE } from '../actions/article';
export default store => next => action => {
// Prepare variables for fetch()
const articleApiListUrl = `${articleApiUrl}list`;
const headers = new Headers({ 'Content-Type': 'application/json', 'x-api-key': articleApiKey });
const body = JSON.stringify({ ids: [action.articleId] });
const method = 'POST';
// Quit when action is not to be handled by this middleware
if (action.type !== ARTICLE_REQUEST) {
return next(action)
}
// Pass on current action
next(action);
// Call fetch, dispatch followup actions and return Promise
return fetch(articleApiListUrl, { headers, method, body })
.then(response => response.json());
.then(response => {
if (response.error) {
next({ type: ARTICLE_FAILURE, error: response.error });
} else {
next({ type: ARTICLE_SUCCESS, article: response.articles[0] });
}
});
}
我真的很想知道如何测试这个异步代码。我想看看后续操作是否会被正确分派,也许fetch 调用是否被正确的 URL 和参数调用。谁能帮帮我?
PS:我使用的是thunk,虽然我不确定它的功能,因为我只是按照另一个代码示例进行操作
【问题讨论】:
标签: unit-testing testing redux react-redux redux-thunk