Skip to content

Instantly share code, notes, and snippets.

@sandwichsudo
Last active July 27, 2017 10:21
Show Gist options
  • Save sandwichsudo/c5a54cacc840a99a0d6253644a451f3b to your computer and use it in GitHub Desktop.
Save sandwichsudo/c5a54cacc840a99a0d6253644a451f3b to your computer and use it in GitHub Desktop.
Concise testable actions
import searchService from '../../../services/search/searchService';
import { actionTypes } from '../RepoSearchConstants';
export const fetchRepos = () => async (dispatch) => {
let error = '';
dispatch({
type: actionTypes.REQUEST_START,
});
try {
const { items } = await searchService.repoSearch();
dispatch({
type: actionTypes.UPDATE_RESULTS,
items,
});
}
catch ({ message }) {
error = message;
}
dispatch({
type: actionTypes.REQUEST_COMPLETE,
error,
});
};
import { fetchRepos } from './RepoSearchActions';
import searchService from '../../../services/search/searchService';
import { actionTypes } from '../RepoSearchConstants';
jest.mock('../../../services/search/searchService');
describe('repo search actions', () => {
describe('fetchRepos', () => {
it('should call searchService.repoSearch and dispatch actions', async () => {
searchService.__setMockReposSearch(Promise.resolve({
items: 'foo',
}));
const dispatch = jest.fn();
await fetchRepos()(dispatch);
expect(searchService.repoSearch).toHaveBeenCalled();
expect(dispatch.mock.calls).toEqual([
[{ type: actionTypes.REQUEST_START }],
[{ type: actionTypes.UPDATE_RESULTS, items: 'foo' }],
[{ type: actionTypes.REQUEST_COMPLETE, error: '' }]
]);
});
it('should dispatch error action when service throws an exception', async () => {
searchService.__setMockReposSearch(Promise.reject({
message: 'Something went wrong',
}));
const dispatch = jest.fn();
await fetchRepos()(dispatch);
expect(searchService.repoSearch).toHaveBeenCalled();
expect(dispatch.mock.calls).toEqual([
[{ type: actionTypes.REQUEST_START }],
[{ type: actionTypes.REQUEST_COMPLETE, error: 'Something went wrong' }]
]);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment