-
-
Save upandfine/80decbb78fa739c2299a32182fa9d0e9 to your computer and use it in GitHub Desktop.
Jest test for Redux-Observable epic.
This file contains hidden or 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 Rx from 'rxjs'; | |
import { ActionsObservable } from 'redux-observable'; | |
import { ajax } from 'rxjs/observable/dom/ajax'; | |
import { loadGames } from '../../src/epics/games'; | |
import { ajax } from 'rxjs/observable/dom/ajax'; | |
jest.mock('rxjs/observable/dom/ajax', () => ({ | |
ajax: jest.fn(), | |
})); | |
const mockImplementation = () => { | |
let callCount = 0; | |
const responses = [ | |
null, | |
[{ | |
gameId: 0, | |
}], [{ | |
gameId: 0, | |
}], [{ | |
gameId: 0, | |
}], [{ | |
gameId: 0, | |
}], | |
]; | |
return Rx.Observable.create((observer) => { | |
if (callCount === 0) { | |
observer.next(null); | |
} else { | |
observer.next({ response: responses[callCount] }); | |
} | |
callCount += 1; | |
observer.complete(); | |
}); | |
}; | |
test('loadGames polls games', () => { | |
const inputValues = { | |
a: { type: 'LOAD_GAMES', payload: { date: '2010-10-10' } }, | |
b: { type: 'LOAD_GAMES_CANCEL', payload: {} }, | |
}; | |
const expectedValues = { | |
a: { | |
type: 'SET_GAMES_LOADING', | |
payload: { date: '2010-10-10' }, | |
}, | |
b: { | |
type: 'RECEIVE_GAMES', | |
payload: { | |
date: '2010-10-10', | |
items: [{ | |
gameId: 0, | |
}], | |
}, | |
}, | |
}; | |
const inputMarble = 'a-----b'; | |
const expectedMarble = '-abbbb------'; | |
const ts = new Rx.TestScheduler((actual, expected) => { | |
expect(actual).toEqual(expected); | |
}); | |
const action$ = new ActionsObservable(ts.createHotObservable(inputMarble, inputValues)); | |
const outputAction = loadGames(action$, null, ts, 10, 10); | |
const ajaxMock = jest.fn(); | |
ajaxMock.mockReturnValue(mockImplementation()); | |
ajax.mockImplementation(ajaxMock); | |
ts.expectObservable(outputAction).toBe(expectedMarble, expectedValues); | |
ts.flush(); | |
expect(ajaxMock).toHaveBeenCalledTimes(1); | |
expect(ajaxMock).toHaveBeenCalledWith({ | |
url: '../games/date/2010-10-10', | |
responseType: 'json', | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment