[Redux-Observable && Unit Testing] Mocking an ajax request when testing epics
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的更多相关文章
- Extjs4.0以上版本 Ext.Ajax.request请求的返回问题
Ext.Ajax.request({ url: posturl, method: 'POST', params: { ClassName: 'XXXX', FuncName: 'XXXX', para ...
- [转] form.getForm().submit的用法及Ext.Ajax.request的小小区别
原文地址:http://blog.csdn.net/hongleidy5000/article/details/7329325 if (!formDetail.getForm().isValid()) ...
- (ExtJs 3.4)Ext.Ajax.request的同步请求实现
ext3.0之前都是这样来提交:var responsea = Ext.lib.Ajax.getConnectionObject().conn;responsea.open("POST&qu ...
- Extjs-Ext.Ajax.request设置超时
ExtJs的Ajax提交主要是:Ext.Ajax.request或form1.getForm().submit,超时时间默认是30秒. 很多时候,后台处理比较多,往往需要超出30秒的限制.此时,可以通 ...
- EXTJS 资料 Ext.Ajax.request 获取返回数据
下面是一个登陆页面调用的EXTJS login function,通过 url: '/UI/HttpHandlerData/Login/Login.ashx',获取返回登陆账户和密码! Ext.onR ...
- Ext.Ajax.request()方法和FormPanel.getForm().submit()方法,都返回success()方法的差异
我还是不发表到博客园首页吧,要不然还是要被取消,>_< 还是言归正传吧,关于Ext.Ajax.request()方法和FormPanel.getForm().submit()方法返回suc ...
- 【转】Ext.ajax.request 中的success和failure
原文链接:Ext.ajax.request 中的success和failure Ajax request对象的success事件表示request过程中没有发生错误,和自己的业务逻辑无关, 如果访问不 ...
- Ext.Ajax.request同步请求
导读: ajax分为2种,一种是同步,一种是异步同步:代码执行完了之后才执行后面的代码 异步:代码刚执行,后面的代码就马上接着执行了,不管前面的代码是否执行完异步的情况下,要获得返回信息,就需要在异步 ...
- Detecting an Ajax request in PHP
1:index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...
随机推荐
- P4287 [SHOI2011]双倍回文(回文树)
题目描述 记字符串 w 的倒置为 w^R^ .例如 (abcd)^R^=dcba , (abba)^R^=abba . 对字符串x,如果 x 满足 x^R^=x ,则称之为回文:例如abba是一个回文 ...
- .NET 将 .config 文件嵌入到程序集
原文:.NET 将 .config 文件嵌入到程序集 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/Iron_Ye/article/details/ ...
- 2014 CodingTrip - 携程编程大赛 (预赛第一场)
1001: 可以证明(扩展欧几里得),只要卡片中有两个卡片互素,旁边点就是可达的. 因此只需要算出所有卡片不互素的情况有多少种,可用容斥原理. #include <cstdio> #inc ...
- java枚举在android项目应用
今天修复一个公司非常早曾经的android应用功能,里面的代码逻辑已经全然错乱,然后发现返回的数据全然不正确了.然后修复了整整两天.然后我又一次整理了一遍,重构就算不上了. 然后就用上了枚举. 什么是 ...
- redis之字符串命令源代码解析(二)
形象化设计模式实战 HELLO!架构 redis命令源代码解析 在redis之字符串命令源代码解析(一)中讲了get的简单实现,并没有对 ...
- OpenCV学习笔记09--通过cvPtr2D或指针算法绘制图形
练习:创建一个1000*1000的三通道图像,将其元素所有置0.以(200,50)和(400,200)为顶点绘制一个绿色平面 我们能够用两种方法来实现这一功能,一个是使用cvPtr2D,可是因为使用了 ...
- vue15 自定义元素指令、标签指令
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- FPGA设计中的电源管理(转载)
过去,FPGA设计者主要关心时序和面积使用率问题.但随着FPGA不断取代ASSP和ASIC器件,设计者们现正期望能够开发低功耗设计,在设计流程早期就能对功耗进行正确估算,以及管理和对与FPGA相关的各 ...
- 360动态加载的Android插件框架
github地址:https://github.com/Qihoo360/DroidPlugin DroidPlugin 是360手机助手在Android系统上实现了一种新的插件机制:它可以在无需安装 ...
- Sqoop Export原理和详细流程讲解
Sqoop Export原理 Sqoop Export详细流程讲解