0
我有一个中间件,等待ARTICLE_REQUEST
操作,执行fetch
并在完成提取时调度ARTICLE_SUCCESS
或ARTICLE_FAILURE
操作。像这样使用thunk减少测试异步中间件
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
虽然我没有绝对的把握它的功能,因为我只是跟着另一个代码示例
问题是不是垫片获取,我可以使用'nock',而是如何测试异样 – Lukas
你使用什么测试框架? – philipp
我用酶与笑话 – Lukas