[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 ...
随机推荐
- python 异步IO
参考链接:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143208573 ...
- ECNUOJ 2619 询问
询问 Time Limit:2000MS Memory Limit:65536KBTotal Submit:286 Accepted:70 Description Pollux最近对字符串匹配很感兴 ...
- oc数据类型分类
OC数据类型能够分为 基本类型.构造类型.指针类型.空类型 基本类型可分为 整型.字符型.枚举型.浮点型(float类型.double类型) 构造类型可分为 数组类型.结构体类型.公用体类型 指针类型 ...
- DECLARE CURSOR (Transact-SQL)
Defines the attributes of a Transact-SQL server cursor, such as its scrolling behavior and the query ...
- Cookie与Session的区别与联系及生命周期
Cookie与Session的区别与联系及生命周期 一.Session与Cookie介绍 这些都是基础知识,不过有必要做深入了解.先简单介绍一下. 二者的定义: 当你在浏览网站的时候,WEB 服务器会 ...
- Redis封装之String
RedisBase类 /// <summary> /// RedisBase类,是redis操作的基类,继承自IDisposable接口,主要用于释放内存 /// </summary ...
- AtCoderAGC003D Anticube
Description: 给定一个序列\(a\),要求选出最多的序列元素并保证两两元素的乘积不为立方数 Solution: 我们考虑哪些因子是有用的,如果一个因子的指数\(>3\),我们可以将他 ...
- 【Docker入门】
目录 Linux容器 Docker的优势 Docker三大概念 安装使用Docker 补充知识 [Docker入门] 发布文章 "qq_41964425" @ *** 所谓Dock ...
- WP8 学习笔记(001_环境配置)
Step 1 WP8 的开发要求64位操作系统,Windows 8及以上版本,需要激活版,建议网上买一个注册码.详见安装双系统. Step 2 安装好系统并已经激活之后,需要安装Windows Ph ...
- Swift学习笔记(3)--基本运算符
基本运行符: +(加法.正数) - (减法.负数) * (乘法) / (除法) % (求余) : 在Swift中,求余可以是浮点数求余. &&(逻辑与) || (逻辑或) ^ (逻 ...