1. 程式人生 > >Some Thoughts On Testing React/Redux Applications

Some Thoughts On Testing React/Redux Applications

Testing Redux

Reducers

Testing reducers should be straight forward. Same data in, same data out. Another thing to consider is to use action creators when creating the action for the reducer under test. By taking this approach we don’t need to explicitly test any action creators, as this might involve some overhead without real benefits.

it('should handle ADD_TODO', () => {
expect(
todos([], addTodo('Test AddTodo') // use the action creator
).toEqual([
{
text: 'Test AddTodo',
completed: false,
id: 0
}
])
})

Action Creator

See reducers. No explicit action creator tests. See the following tests, we’re rewriting the action creator to be able to test it.

it('addTodo should create ADD_TODO action', () => {
expect(addTodo('Test addTodo')).toEqual({
type: types.ADD_TODO,
text: 'Test addTodo'
})
})

Even a better example.

const completeAll = () => ({ type: types.COMPLETE_ALL })
expect(completeAll()).toEqual({
type: types.COMPLETE_ALL
})

By creating the actions via action creators when testing reducers, we’re already verifying that the action creators work as expected.

Async Action Creators with Redux-Thunk

Testing includes mocking the store or mocking a specific call. There are a couple of possible approaches, but best is to consult the redux documentation.

The following example is taken straight from redux “Writing Tests” section.

it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', () => {
nock('http://example.com/')
.get('/todos')
.reply(200, { body: { todos: ['do something'] }})

const expectedActions = [
{ type: types.FETCH_TODOS_REQUEST },
{ type: types.FETCH_TODOS_SUCCESS,
body: { todos: ['do something'] }
}]
const store = mockStore({ todos: [] })

return store.dispatch(actions.fetchTodos())
.then(() => { // return of async actions
expect(store.getActions()).toEqual(expectedActions)
})
})

Yes, asynchronous action creators based on redux-thunk for example should be tested when possible.

Async Action Creators with Redux-Saga

Testing asynchronous actions with redux-saga is as simple as calling next on the generated object. Take a look at the shopping-cart test example:

test('getProducts Saga test', function (t) {
const generator = getAllProducts(getState)
let next = generator.next(actions.getAllProducts())

t.deepEqual(next.value, call(api.getProducts),
"must yield api.getProducts"
)

next = generator.next(products)

t.deepEqual(next.value, put(actions.receiveProducts(products)),
"must yield actions.receiveProducts(products)"
)
t.end()
})

We don’t have to deal with mocking api calls and other asynchronous actions, as we only verify if the returned action is the expected one. This also enables us to verify that the actions are returned in the correct order.

Testing React-Redux

No testing of connected components nor verifying that mapDispatchToProps returns expected results at the moment. Regarding the first, I would like to hear some feedback. It could also be seen as a type of integration test, but I would like to hear about the real benefits, besides testing if react-redux is passing the updated state to a given component under test. Regarding testing mapDispatchToProps, under regular circumstances, we’re only composing action creators with dispatch.

In regards to the connect method, mapStateToProps might be interesting to test, especially when defined as a selector. This depends on the fact if logic is involved when selecting the state and might make a lot of sense in given situations.

Like mentioned above, I would like to hear feedback on how you approach testing the react-redux specific parts.

相關推薦

Some Thoughts On Testing React/Redux Applications

Testing ReduxReducersTesting reducers should be straight forward. Same data in, same data out. Another thing to consider is to use action creators when cre

Some Thoughts on Android's new ConstraintLayout and Android Studio's new Design Editor

At this year's IO Google introduced a new layout - the ConstraintLayout - and also presented it's totally revamped la

Some thoughts on resistance training volume and hypertrophy

The design of the studyThe study compared three groups performing either 1 set (1-SET), 3 sets (3-SET) or 5 sets (5-SET) of the same exercises, three times

react-router與react-redux跳轉後保存store數據(基於"react-router": "^2.8.0")

spa imp pan item 介紹 評論 tdi else mount 1.router引入 import { Route, IndexRoute, Router, hashHistory, browserHistory } from ‘react-router‘;

React + Redux + express+ antd 架構的認識

tor 需要 抓包 開發 們的 store 數據 捕獲 項目   在過去的兩周裏,我使用這套技術棧進行項目頁面的開發。下面是我個人的對於項目的一些看法:   首先:是項目的調試,我深表壓力很大,項目是使用fibber去抓包調試的,也不知道我們項目的負責人,怎麽能的我在每次更

react-router搭配react-redux無法監聽路由變化的問題

不必要 默認 cti 傳遞 通過 nbsp fun urn style 在react中,要將react組件連接到redux中,通常會這樣包裝組件 class Home extends Component { } function select(state)

react-redux 的 todomvc

todomvc下文有項目文件下載 在項目目錄中執行 npm install 安裝依賴,install start 啟動項目,網頁會自動打開index.jsimport React from ‘react‘import { render } from ‘react-dom‘import { createSto

react+redux+webpack+git技術棧

tps .net read nor 無法 mac icon ear es5 1 一、git bash here 2 mdkr 3 cnpm init -y 4 ls -a 5 ls -l 6 ls -la隱藏的也可查看 7 cat packag

React+router和react+redux使用過程的記錄

app.js 描述 集成 關系 route false 操作 之間 ade 1、集成react+redux的場景。 在不同的路由頁面下,控制公共的頭部顯示和隱藏等功能。因為路由和Header之間不是直接的父組件和子組件的關系,所以通過pros傳參滿足不了。這個時候引入red

利用create-react-app結合react-reduxreact-router4構建單頁應用

app pro json 裝飾器 ans install 組件 orm alt 1.創建項目:   a.全局安裝create-react-app: npm install create-react-app -g b.執行create-react-app

React+Redux項目實戰總結

ise github class a markdown push mark ref 目錄 tmpl 本項目實戰是簡化版的大眾點評wap版 技術棧 react + redux + react-router-dom mock數據使用的是 koa + koa-router 項目源

ReduxReact-Redux的實現(三):中間件的原理和applyMiddleware、Thunk的實現

調用 map 介紹 typeof 觀察者 ets 返回 async 基本原理 現在我們的Redux和React-Redux已經基本實現了,在Redux中,觸發一個action,reducer立即就能算出相應的state,如果我要過一會才讓reducer計算state呢怎麽辦

react/redux中使用Immutable

可控 有一個 size creat gpo 容易 最好 shc get 有人說 Immutable 可以給 React 應用帶來數十倍的提升,也有人說 Immutable 的引入是近期 JavaScript 中偉大的發明,因為同期 React 太火,它的光芒被掩蓋了。這些至

react-redux基本使用

react redux 基本使用 圖解: 代碼: var createStore = require(‘redux‘).createStore var indexStore = createStore(function(state=0,action){ switch(action.type){

react-redux進階

react-redux進階一、 安裝: npm install redux react-redux 二、入口文件:index.jsx: 引入: 創建reducer: 創建容器: 將容器綁定到屬性: 完整代碼: var React = require(‘react‘) var ReactDom = re

react + redux + router寫一個todo

有用 Redux 升級 開發 代碼 git 我只 ima 參考 概述 最近學習redux,打算用redux + router寫了一個todo。記錄下來,供以後開發時參考,相信對其他人也有用。 註意: 我只實現了Footer組件的router,其它組件的實現方法是類似的。

React-redux原理探索

提示 about IE out req message == 通知 sed 先看一段react-redux代碼再探索原理 import React from ‘react‘; import { render } from ‘react-dom‘; import { cre

redux超易學三篇之二(開始使用react-redux

同時 In 放置 higher CA thead ble 分支 成長 其實 redux 真正讓人感到混亂的還是在 react-redux 的使用中。 請配合完整代碼參考~:完整源代碼 也不是說混亂,主要是網上 推崇 最佳實踐。學習一個新東西的時候,本來就很陌生,上來就用最佳

redux超易學三篇之三(一個邏輯完整的react-redux)

沒有 難度 傳播 ppr 優化 調用 cer emc spa 配合源代碼學習吧~ : 我是源代碼 這一分支講的是 如何完整地(不包含優化,也沒有好看的頁面) 搭建一個 增刪改查 的 react-redux 系統 不同於上一節的 react-redux,這裏主要采用 函數式

手寫 reduxreact-redux

create reat context 結果 生命周期 connect 組件 ren DC 1.手寫 redux redux.js /** * 手寫 redux */ export function createStore(reducer) { // 當前狀態