Skip to content

Instantly share code, notes, and snippets.

@dmtrmrtnv
Created November 28, 2017 14:15
Show Gist options
  • Save dmtrmrtnv/cf16480e7df05d1f7ed3fa6a717df9ce to your computer and use it in GitHub Desktop.
Save dmtrmrtnv/cf16480e7df05d1f7ed3fa6a717df9ce to your computer and use it in GitHub Desktop.
Jest test for Redux-Observable epic.
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