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. who---显示目前登录系统的用户信息

    who命令是显示目前登录系统的用户信息.执行who命令可得知目前有那些用户登入系统,单独执行who命令会列出登入帐号,使用的终端机,登入时间以及从何处登入或正在使用哪个X显示器. 语法 who(选项) ...

  2. MySql中允许远程连接

    要达到这个目的需要实现两点 开通用户权限 解除本地绑定 开通用户权限 首先登陆服务器端的mysql //不使用空格可以直接登陆 mysql -u用户名 -p密码 mysql> use mysql ...

  3. CsGL着色的三角形

    转自NeHe教程 public override void Draw() { // Here's Where We Do All The Drawing glClear(GL_COLOR_BUFFER ...

  4. [Poi] Build a Vue App with Poi

    Poi uses the Vue babel presets by default, so there is no additional install required to get up-and- ...

  5. 【v2.x OGE教程 17】事务处理

    游戏代码中常常有些逻辑须要处理.因此OGE引擎加入了一个IUpdateHandler的类. IUpdateHandler类是OGE引擎中使用频率很之高的组件之中的一个,其本身是一个接口.内部有onUp ...

  6. 携手互联网企业10巨头设VC基金

    包括小米科技.盛大集团.人人网.掌趣科技.游族网络.龙图游戏.蓝港互动.37游戏.星辉互动娱乐.博雅互动等10家知名互联网企业作为出资人(LP)的优格创投基金近日正式成立. 众所周知,伴随着移动互联网 ...

  7. Ubuntu16.04安装官方Firefox 火狐浏览器 延长支持版(Extended Support Release, 简称“ESR”)

    Ubuntu16.04安装官方Firefox 火狐浏览器 延长支持版(Extended Support Release, 简称“ESR”) 延长支持版本(Extended Support Releas ...

  8. 如何批量ping地址查看网络是否畅通

    测试环境搬迁后,需要批量去ping所有机器的IP,看网络是否畅通 测试思路: [weblogic@pays03pre_BankVerify luyantest]$ ping -c 1 172.29.1 ...

  9. CSUOJ 1525 Algebraic Teamwork

    Problem A Algebraic Teamwork The great pioneers of group theory and linear algebra want to cooperate ...

  10. java设计模式--事件监听器模式(观察者模式)

    这两个模式实质上很简单,在实际项目中也是非常常用的.但却被有些人说的云里雾里,这里用白话解释一下. 本质上两者都是同一个模式.专业的说法是这样的(觉得绕口的请直接转到白话解释部分,再回头来看下面这几句 ...