Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import configureStore from 'redux-mock-store';
- import thunk from 'redux-thunk';
- import { AbortController } from 'abortcontroller-polyfill/dist/abortcontroller';
- import promiseMiddleware from '../util/promiseMiddleware';
- import { delay } from '../shared/fetchApi';
- import {
- setProfile,
- setCourses,
- } from './actions';
- const mockStore = configureStore([thunk, promiseMiddleware]);
- const user = { name: '11' };
- const courses = [{ id: '5', name: 'c5' }, { id: '6', name: 'c6' }];
- describe('redux actions', () => {
- it('gets user profile', async () => {
- // mock fetch (we could pass fetch in action creators to avoid this global thing, but I think it's more annoying)
- global.fetch = async () => ({
- ok: true,
- json: async () => user,
- });
- // mock store
- const store = mockStore({});
- await store.dispatch(setProfile());
- const action = store.getActions()[0];
- expect(action.value).toEqual(user);
- });
- it('gets courses', async () => {
- // mock fetch
- global.fetch = async () => ({
- ok: true,
- json: async () => ({ data: { courses } }),
- });
- // mock store
- const store = mockStore({ data: {} });
- await store.dispatch(setCourses({ refetch: true }));
- const action = store.getActions()[0];
- expect([...action.value.courses.values()]).toEqual(courses);
- });
- it('can cancel courses fetching', async () => {
- // mock fetch
- global.fetch = async (url, { signal }) => {
- const cancellation = new Promise((_, reject) => {
- signal.addEventListener('abort', () => reject(new Error('aborted')), { once: true });
- });
- const fetch = () => delay(500).then(() => ({
- ok: true,
- json: async () => ({ data: { courses } }),
- }));
- return Promise.race([cancellation, fetch()]);
- };
- // mock store
- const store = mockStore({ data: {} });
- const controller = new AbortController();
- try {
- const promise = store.dispatch(setCourses({ refetch: true, signal: controller.signal }));
- controller.abort();
- await promise;
- } catch (e) {
- expect(true);
- const action = store.getActions()[0];
- expect(action).toBe(undefined);
- }
- });
- });
Add Comment
Please, Sign In to add comment