Guest User

Untitled

a guest
Feb 19th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. import configureStore from 'redux-mock-store';
  2. import thunk from 'redux-thunk';
  3. import { AbortController } from 'abortcontroller-polyfill/dist/abortcontroller';
  4. import promiseMiddleware from '../util/promiseMiddleware';
  5. import { delay } from '../shared/fetchApi';
  6. import {
  7. setProfile,
  8. setCourses,
  9. } from './actions';
  10.  
  11. const mockStore = configureStore([thunk, promiseMiddleware]);
  12.  
  13. const user = { name: '11' };
  14. const courses = [{ id: '5', name: 'c5' }, { id: '6', name: 'c6' }];
  15.  
  16. describe('redux actions', () => {
  17. it('gets user profile', async () => {
  18. // mock fetch (we could pass fetch in action creators to avoid this global thing, but I think it's more annoying)
  19. global.fetch = async () => ({
  20. ok: true,
  21. json: async () => user,
  22. });
  23. // mock store
  24. const store = mockStore({});
  25. await store.dispatch(setProfile());
  26. const action = store.getActions()[0];
  27. expect(action.value).toEqual(user);
  28. });
  29.  
  30. it('gets courses', async () => {
  31. // mock fetch
  32. global.fetch = async () => ({
  33. ok: true,
  34. json: async () => ({ data: { courses } }),
  35. });
  36. // mock store
  37. const store = mockStore({ data: {} });
  38. await store.dispatch(setCourses({ refetch: true }));
  39. const action = store.getActions()[0];
  40. expect([...action.value.courses.values()]).toEqual(courses);
  41. });
  42.  
  43. it('can cancel courses fetching', async () => {
  44. // mock fetch
  45. global.fetch = async (url, { signal }) => {
  46. const cancellation = new Promise((_, reject) => {
  47. signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
  48. });
  49. const fetch = () => delay(500).then(() => ({
  50. ok: true,
  51. json: async () => ({ data: { courses } }),
  52. }));
  53. return Promise.race([cancellation, fetch()]);
  54. };
  55. // mock store
  56. const store = mockStore({ data: {} });
  57.  
  58. const controller = new AbortController();
  59. try {
  60. const promise = store.dispatch(setCourses({ refetch: true, signal: controller.signal }));
  61. controller.abort();
  62. await promise;
  63. } catch (e) {
  64. expect(true);
  65. const action = store.getActions()[0];
  66. expect(action).toBe(undefined);
  67. }
  68. });
  69. });
Add Comment
Please, Sign In to add comment