Skip to content

Commit

Permalink
test: 💍 add basic epic plugin tests
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jun 17, 2018
1 parent 3f4ccc3 commit 267ac1c
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"standard": "11.0.1",
"redux": "3.7.2",
"react-redux": "5.0.7",
"rxjs": "5.5.11",
"rxjs": "^6.2.1",
"react": "16.4.0",
"react-dom": "16.4.0",
"@storybook/react": "3.4.7",
Expand Down
68 changes: 68 additions & 0 deletions src/plugins/__tests__/epic.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import {createStore} from '../../'
import pluginDispatch from '../dispatch'
import pluginReducer from '../reducer'
import pluginEpic from '../epic'

const delay = time => new Promise(resolve => setTimeout(resolve, time))

const createStoreWithPlugin = (epic, reducer = state => state) => {
return createStore({}, [
pluginDispatch(),
pluginReducer(reducer),
pluginEpic(epic)
])
}

describe('plugin', () => {
describe('epics', () => {
it('is a function', () => {
expect(typeof pluginEpic).toBe('function')
})

it('throws if epic is not a function', () => {
expect(() => {
createStore(123)
}).toThrow()
})

it('works', async () => {
const log = []
const epic = (observable, store) => {
return {
subscribe (sink) {
observable.subscribe({
next: action => {
if (action.type === 'PING') {
sink.next({type: 'PONG'})
}
}
})
}
}
}
const store = createStoreWithPlugin(epic)
const dispatch = store.dispatch

store.dispatch = (action) => {
log.push(action)
dispatch(action)
}

await delay(100)

store.dispatch({
type: 'PING'
})

store.dispatch({
type: 'NOT_PING'
})

expect(log).toEqual([
{ type: 'PING' },
{ type: 'PONG' },
{ type: 'NOT_PING' }
])
})
})
})
12 changes: 10 additions & 2 deletions src/plugins/epic.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import $$observable from 'symbol-observable'

const plugin = (epic) => store => {
const dispatch = store.dispatch
if (process.env.NODE_ENV !== 'production') {
if (typeof epic !== 'function') {
throw new TypeError('epic must be a function that receives an observable and returns and observable.')
}
}

const observable = {
subscribe (observer) {
const dispatch = store.dispatch
let live = true

store.dispatch = (action) => {
console.log('A', action)
dispatch(action)

if (live) {
Expand All @@ -27,7 +33,9 @@ const plugin = (epic) => store => {
}
}

epic(observable, store)(dispatch)
epic(observable, store).subscribe({
next: (action) => store.dispatch(action)
})
}

export default plugin

0 comments on commit 267ac1c

Please sign in to comment.