Last active
November 2, 2018 08:49
-
-
Save MichaelBorde/4d0894fa6c8cc73c7ada4f7dac6ca348 to your computer and use it in GitHub Desktop.
runSaga helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { EventEmitter } from 'events'; | |
import { runSaga as reduxRunSaga, SagaIterator } from 'redux-saga'; | |
import { Action } from 'typescript-fsa'; | |
interface SagaInput { | |
input?: Action<any>; | |
inputs?: Array<Action<any>>; | |
state?: any; | |
saga: () => SagaIterator; | |
} | |
type Dispatch = (...actions: Array<Action<any>>) => void; | |
interface SagaOutput { | |
dispatched: Array<Action<any>>; | |
dispatch: Dispatch; | |
} | |
export async function runSaga(run: SagaInput): Promise<SagaOutput> { | |
const { input, inputs = [], state = {}, saga } = run; | |
const emitter = new EventEmitter(); | |
emitter.setMaxListeners(100); | |
const dispatched: Array<Action<any>> = []; | |
const dispatch = (...actions: Array<Action<any>>) => | |
actions.forEach(a => emitter.emit('action', a)); | |
const promise = reduxRunSaga( | |
{ | |
subscribe: (callback: any) => { | |
emitter.on('action', callback); | |
return () => { | |
emitter.removeListener('action', callback); | |
}; | |
}, | |
dispatch: (action: Action<any>) => dispatched.push(action), | |
getState: () => state | |
}, | |
saga | |
); | |
const allInputs = input ? [input] : inputs; | |
dispatch(...allInputs); | |
await promise; | |
return { dispatched, dispatch }; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('Window manager saga', () => { | |
let saga: () => SagaIterator; | |
beforeEach(() => { | |
saga = windowManagerSaga(); | |
}); | |
describe('on splash ready', () => { | |
it('should put action to show splash', async () => { | |
const { dispatched } = await runSaga({ | |
saga, | |
input: splashActions.ready() | |
}); | |
expect(dispatched).toContainEqual(splashActions.show()); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment