Add ability to record custom actions by WaitMiddleware

This commit is contained in:
Jerko Steiner 2019-09-11 12:05:36 +07:00
parent c2c49c5f7a
commit 67e81d6b80
2 changed files with 25 additions and 5 deletions

View File

@ -110,7 +110,7 @@ describe('WaitMiddleware', () => {
describe('record', () => {
it('records pending actions', async () => {
it('records pending actions by default', async () => {
const wm = new WaitMiddleware()
const store = getStore(wm)
const recorder = wm.record()
@ -127,6 +127,16 @@ describe('WaitMiddleware', () => {
})
await promise
})
it('records custom actions', async () => {
const wm = new WaitMiddleware()
const store = getStore(wm)
const recorder = wm.record(action => action.type.startsWith('test'))
store.dispatch({type: 'test1'} as any)
store.dispatch({type: 'tes'} as any)
store.dispatch({type: 'test3'} as any)
expect(recorder.getActionTypes()).toEqual(['test1', 'test3'])
})
})
})

View File

@ -14,10 +14,10 @@ export class WaitMiddleware {
}
/**
* Starts recording pending actions and returns the recorder.
* Starts recording actions and returns the recorder.
*/
record(): Recorder {
const recorder = new Recorder()
record(shouldRecord: ShouldRecord = defaultShouldRecord): Recorder {
const recorder = new Recorder(shouldRecord)
this.recorders.push(recorder)
return recorder
}
@ -91,15 +91,25 @@ export class WaitMiddleware {
}
}
/**
* Returns true when an action should be recorded, false otherwise
*/
export type ShouldRecord = (action: AnyAction) => boolean
export const defaultShouldRecord: ShouldRecord =
(action: AnyAction) => 'status' in action && action.status === 'pending'
class Recorder {
protected actionTypes: string[] = []
constructor(protected readonly shouldRecord: ShouldRecord) {}
getActionTypes(): string[] {
return this.actionTypes.slice()
}
record(action: AnyAction) {
if ('status' in action && action.status === 'pending') {
if (this.shouldRecord(action)) {
this.actionTypes.push(action.type)
}
}