Often in unit tests we are focussing on the logic involved in crafting a network request, & how we respond to the result. The external service is unlikely to be under our control, so we need a way to ‘mock’ the Ajax request in a way that allows us to focus on the logic. In this lesson we’ll see how we can pass in dependencies into epics to make testing things Ajax requests easier.

In a real world React app, for one epic, we might have some dependecies. For example, ajax call. To make it easy for testing, we can make those deps as injectable deps.

When creating root epic:

import { createEpicMiddleware, combineEpics } from 'redux-observable';
import { ajax } from 'rxjs/observable/dom/ajax';
import rootEpic from './somewhere'; const epicMiddleware = createEpicMiddleware(rootEpic, {
dependencies: { getJSON: ajax.getJSON }
});

Using it in Epic:

// Notice the third argument is our injected dependencies!
const fetchUserEpic = (action$, store, { getJSON }) =>
action$.ofType('FETCH_USER')
.mergeMap(({ payload }) =>
getJSON(`/api/users/${payload}`)
.map(response => ({
type: 'FETCH_USER_FULFILLED',
payload: response
}))
);

---------------Test example ---------------------

index.js, root setup

import {createStore, applyMiddleware, compose} from 'redux';
import {Provider} from 'react-redux';
import reducer from './reducers';
import { ajax } from 'rxjs/observable/dom/ajax'; import {createEpicMiddleware} from 'redux-observable';
import {rootEpic} from "./epics/index"; const epicMiddleware = createEpicMiddleware(rootEpic, {
dependencies: {
ajax
}
}); const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore(
reducer,
composeEnhancers(
applyMiddleware(epicMiddleware)
)
);

Epic function:

import {Observable} from 'rxjs';
import {combineEpics} from 'redux-observable';
import {CANCEL_SEARCH, receiveBeers, searchBeersError, searchBeersLoading, SEARCHED_BEERS} from "../actions/index"; const beers = `https://api.punkapi.com/v2/beers`;
const search = (term) => `${beers}?beer_name=${encodeURIComponent(term)}`; export function searchBeersEpic(action$, store, deps) {
return action$.ofType(SEARCHED_BEERS)
.debounceTime(, deps.scheduler)
.filter(action => action.payload !== '')
.switchMap(({payload}) => { // loading state in UI
const loading = Observable.of(searchBeersLoading(true)); // external API call
const request = deps.ajax.getJSON(search(payload))
.takeUntil(action$.ofType(CANCEL_SEARCH))
.map(receiveBeers)
.catch(err => {
return Observable.of(searchBeersError(err));
}); return Observable.concat(
loading,
request,
);
})
} export const rootEpic = combineEpics(searchBeersEpic);

Test code:

import {Observable} from 'rxjs';
import {ActionsObservable} from 'redux-observable';
import {searchBeersEpic} from "./index";
import {RECEIVED_BEERS, searchBeers, SEARCHED_BEERS_LOADING} from "../actions/index"; it.only('should perform a search', function () {
const action$ = ActionsObservable.of(searchBeers('shane')); const deps = {
ajax: {
getJSON: () => Observable.of([{name: 'shane'}])
}
}; const output$ = searchBeersEpic(action$, null, deps); output$.toArray().subscribe(actions => {
expect(actions.length).toBe(); expect(actions[].type).toBe(SEARCHED_BEERS_LOADING);
expect(actions[].type).toBe(RECEIVED_BEERS);
});
});

Refs: Link

[Redux-Observable && Unit Testing] Mocking an ajax request when testing epics的更多相关文章

  1. Extjs4.0以上版本 Ext.Ajax.request请求的返回问题

    Ext.Ajax.request({ url: posturl, method: 'POST', params: { ClassName: 'XXXX', FuncName: 'XXXX', para ...

  2. [转] form.getForm().submit的用法及Ext.Ajax.request的小小区别

    原文地址:http://blog.csdn.net/hongleidy5000/article/details/7329325 if (!formDetail.getForm().isValid()) ...

  3. (ExtJs 3.4)Ext.Ajax.request的同步请求实现

    ext3.0之前都是这样来提交:var responsea = Ext.lib.Ajax.getConnectionObject().conn;responsea.open("POST&qu ...

  4. Extjs-Ext.Ajax.request设置超时

    ExtJs的Ajax提交主要是:Ext.Ajax.request或form1.getForm().submit,超时时间默认是30秒. 很多时候,后台处理比较多,往往需要超出30秒的限制.此时,可以通 ...

  5. EXTJS 资料 Ext.Ajax.request 获取返回数据

    下面是一个登陆页面调用的EXTJS login function,通过 url: '/UI/HttpHandlerData/Login/Login.ashx',获取返回登陆账户和密码! Ext.onR ...

  6. Ext.Ajax.request()方法和FormPanel.getForm().submit()方法,都返回success()方法的差异

    我还是不发表到博客园首页吧,要不然还是要被取消,>_< 还是言归正传吧,关于Ext.Ajax.request()方法和FormPanel.getForm().submit()方法返回suc ...

  7. 【转】Ext.ajax.request 中的success和failure

    原文链接:Ext.ajax.request 中的success和failure Ajax request对象的success事件表示request过程中没有发生错误,和自己的业务逻辑无关, 如果访问不 ...

  8. Ext.Ajax.request同步请求

    导读: ajax分为2种,一种是同步,一种是异步同步:代码执行完了之后才执行后面的代码 异步:代码刚执行,后面的代码就马上接着执行了,不管前面的代码是否执行完异步的情况下,要获得返回信息,就需要在异步 ...

  9. Detecting an Ajax request in PHP

    1:index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...

随机推荐

  1. caioj 1079 动态规划入门(非常规DP3:钓鱼)(动规中的坑)

    这道题写了我好久, 交上去90分,就是死活AC不了 后来发现我写的程序有根本性的错误,90分只是数据弱 #include<cstdio> #include<algorithm> ...

  2. 一个HelloWorld版的MySQL数据库管理器的设计与实现(源码)

    2011年,实习期间写了一个简单的数据库管理器. 今天,特意整理了下,分享给大家. 有兴趣的同学,可以下载源码,瞧瞧. 源码只有4个类:LoginGUI,DatabaseGUI,Record,MySQ ...

  3. js获取css

    原帖地址:http://kingphp.blog.163.com/blog/static/20042324420120109438458/ 我们通过dom.style获得的属性是有限制的,只能获取ht ...

  4. 用typename和template消除歧义

  5. 基于Linux的智能家居的设计(2)

    1  系统整体设计方案 智能家居系统的是一个实时查询家庭的温湿度.照明控制.自己主动控制的设定.集家庭娱乐.智能安防为一体,大量数据快处理.可靠的系统,因此在硬件和软件上都有非常大的要求,因此在这里进 ...

  6. File的getPath()和getAbsolutePath()和getCanonicalPath()的差别

    这几个方法是有一次无意的发现,我当时也不知道什么意思,就百度了,查到了一些列子: 原文地址http://www.blogjava.net/dreamstone/archive/2007/08/08/1 ...

  7. How to search Installed Updates

    Windows本身的控制面板中自带的搜索,无法根据补丁编号进行搜索 可以将补丁信息导出到文本,再用文本编辑器进行查找 https://www.concurrency.com/blog/w/search ...

  8. GitHub开源控件的使用合集

    Android的加载动画AVLoadingIndicatorView 项目地址: https://github.com/81813780/AVLoadingIndicatorView 首先,在 bui ...

  9. 公司采购 流程flowable例子

    Name: Flowable BPMN 2.0 designer Location: http://flowable.org/designer/update/ 业务描述:1. 公司采购,因为办公用品价 ...

  10. HDU 5446 Unknown Treasure Lucas+中国剩余定理+按位乘

    HDU 5446 Unknown Treasure 题意:求C(n, m) %(p[1] * p[2] ··· p[k])     0< n,m < 1018 思路:这题基本上算是模版题了 ...