mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2024-12-23 09:30:31 +03:00
Migrated orphanVisits reducer to RTK
This commit is contained in:
parent
fd80fd65c9
commit
f81999a4fe
4 changed files with 126 additions and 131 deletions
|
@ -3,7 +3,6 @@ import { combineReducers } from '@reduxjs/toolkit';
|
||||||
import { serversReducer } from '../servers/reducers/servers';
|
import { serversReducer } from '../servers/reducers/servers';
|
||||||
import shortUrlVisitsReducer from '../visits/reducers/shortUrlVisits';
|
import shortUrlVisitsReducer from '../visits/reducers/shortUrlVisits';
|
||||||
import tagVisitsReducer from '../visits/reducers/tagVisits';
|
import tagVisitsReducer from '../visits/reducers/tagVisits';
|
||||||
import orphanVisitsReducer from '../visits/reducers/orphanVisits';
|
|
||||||
import { settingsReducer } from '../settings/reducers/settings';
|
import { settingsReducer } from '../settings/reducers/settings';
|
||||||
import { appUpdatesReducer } from '../app/reducers/appUpdates';
|
import { appUpdatesReducer } from '../app/reducers/appUpdates';
|
||||||
import { sidebarReducer } from '../common/reducers/sidebar';
|
import { sidebarReducer } from '../common/reducers/sidebar';
|
||||||
|
@ -20,7 +19,7 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
|
||||||
shortUrlVisits: shortUrlVisitsReducer,
|
shortUrlVisits: shortUrlVisitsReducer,
|
||||||
tagVisits: tagVisitsReducer,
|
tagVisits: tagVisitsReducer,
|
||||||
domainVisits: container.domainVisitsReducer,
|
domainVisits: container.domainVisitsReducer,
|
||||||
orphanVisits: orphanVisitsReducer,
|
orphanVisits: container.orphanVisitsReducer,
|
||||||
nonOrphanVisits: container.nonOrphanVisitsReducer,
|
nonOrphanVisits: container.nonOrphanVisitsReducer,
|
||||||
tagsList: container.tagsListReducer,
|
tagsList: container.tagsListReducer,
|
||||||
tagDelete: container.tagDeleteReducer,
|
tagDelete: container.tagDeleteReducer,
|
||||||
|
|
|
@ -1,42 +1,19 @@
|
||||||
import { createAction } from '@reduxjs/toolkit';
|
import { createSlice } from '@reduxjs/toolkit';
|
||||||
import { Dispatch } from 'redux';
|
|
||||||
import { OrphanVisit, OrphanVisitType } from '../types';
|
import { OrphanVisit, OrphanVisitType } from '../types';
|
||||||
import { buildReducer } from '../../utils/helpers/redux';
|
|
||||||
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
|
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
|
||||||
import { GetState } from '../../container/types';
|
|
||||||
import { isOrphanVisit } from '../types/helpers';
|
import { isOrphanVisit } from '../types/helpers';
|
||||||
import { ApiErrorAction } from '../../api/types/actions';
|
|
||||||
import { isBetween } from '../../utils/helpers/date';
|
import { isBetween } from '../../utils/helpers/date';
|
||||||
import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common';
|
import { createVisitsAsyncThunk, lastVisitLoaderForLoader } from './common';
|
||||||
import { createNewVisits, CreateVisitsAction } from './visitCreation';
|
import { createNewVisits, CreateVisitsAction } from './visitCreation';
|
||||||
import {
|
import { LoadVisits, VisitsInfo } from './types';
|
||||||
LoadVisits,
|
import { parseApiError } from '../../api/utils';
|
||||||
VisitsFallbackIntervalAction,
|
|
||||||
VisitsInfo,
|
|
||||||
VisitsLoaded,
|
|
||||||
VisitsLoadedAction,
|
|
||||||
VisitsLoadProgressChangedAction,
|
|
||||||
} from './types';
|
|
||||||
|
|
||||||
const REDUCER_PREFIX = 'shlink/orphanVisits';
|
const REDUCER_PREFIX = 'shlink/orphanVisits';
|
||||||
export const GET_ORPHAN_VISITS_START = `${REDUCER_PREFIX}/getOrphanVisits/pending`;
|
|
||||||
export const GET_ORPHAN_VISITS_ERROR = `${REDUCER_PREFIX}/getOrphanVisits/rejected`;
|
|
||||||
export const GET_ORPHAN_VISITS = `${REDUCER_PREFIX}/getOrphanVisits/fulfilled`;
|
|
||||||
export const GET_ORPHAN_VISITS_LARGE = `${REDUCER_PREFIX}/getOrphanVisits/large`;
|
|
||||||
export const GET_ORPHAN_VISITS_CANCEL = `${REDUCER_PREFIX}/getOrphanVisits/cancel`;
|
|
||||||
export const GET_ORPHAN_VISITS_PROGRESS_CHANGED = `${REDUCER_PREFIX}/getOrphanVisits/progressChanged`;
|
|
||||||
export const GET_ORPHAN_VISITS_FALLBACK_TO_INTERVAL = `${REDUCER_PREFIX}/getOrphanVisits/fallbackToInterval`;
|
|
||||||
|
|
||||||
export interface LoadOrphanVisits extends LoadVisits {
|
export interface LoadOrphanVisits extends LoadVisits {
|
||||||
orphanVisitsType?: OrphanVisitType;
|
orphanVisitsType?: OrphanVisitType;
|
||||||
}
|
}
|
||||||
|
|
||||||
type OrphanVisitsCombinedAction = VisitsLoadedAction
|
|
||||||
& VisitsLoadProgressChangedAction
|
|
||||||
& VisitsFallbackIntervalAction
|
|
||||||
& CreateVisitsAction
|
|
||||||
& ApiErrorAction;
|
|
||||||
|
|
||||||
const initialState: VisitsInfo = {
|
const initialState: VisitsInfo = {
|
||||||
visits: [],
|
visits: [],
|
||||||
loading: false,
|
loading: false,
|
||||||
|
@ -46,48 +23,63 @@ const initialState: VisitsInfo = {
|
||||||
progress: 0,
|
progress: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default buildReducer<VisitsInfo, OrphanVisitsCombinedAction>({
|
|
||||||
[`${REDUCER_PREFIX}/getOrphanVisits/pending`]: () => ({ ...initialState, loading: true }),
|
|
||||||
[`${REDUCER_PREFIX}/getOrphanVisits/rejected`]: (_, { errorData }) => ({ ...initialState, error: true, errorData }),
|
|
||||||
[`${REDUCER_PREFIX}/getOrphanVisits/fulfilled`]: (state, { payload }: VisitsLoadedAction) => (
|
|
||||||
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
|
|
||||||
),
|
|
||||||
[`${REDUCER_PREFIX}/getOrphanVisits/large`]: (state) => ({ ...state, loadingLarge: true }),
|
|
||||||
[`${REDUCER_PREFIX}/getOrphanVisits/cancel`]: (state) => ({ ...state, cancelLoad: true }),
|
|
||||||
[`${REDUCER_PREFIX}/getOrphanVisits/progressChanged`]: (state, { payload: progress }) => ({ ...state, progress }),
|
|
||||||
[`${REDUCER_PREFIX}/getOrphanVisits/fallbackToInterval`]: (state, { payload: fallbackInterval }) => (
|
|
||||||
{ ...state, fallbackInterval }
|
|
||||||
),
|
|
||||||
[createNewVisits.toString()]: (state, { payload }: CreateVisitsAction) => {
|
|
||||||
const { visits, query = {} } = state;
|
|
||||||
const { startDate, endDate } = query;
|
|
||||||
const newVisits = payload.createdVisits
|
|
||||||
.filter(({ visit, shortUrl }) => !shortUrl && isBetween(visit.date, startDate, endDate))
|
|
||||||
.map(({ visit }) => visit);
|
|
||||||
|
|
||||||
return { ...state, visits: [...newVisits, ...visits] };
|
|
||||||
},
|
|
||||||
}, initialState);
|
|
||||||
|
|
||||||
const matchesType = (visit: OrphanVisit, orphanVisitsType?: OrphanVisitType) =>
|
const matchesType = (visit: OrphanVisit, orphanVisitsType?: OrphanVisitType) =>
|
||||||
!orphanVisitsType || orphanVisitsType === visit.type;
|
!orphanVisitsType || orphanVisitsType === visit.type;
|
||||||
|
|
||||||
export const getOrphanVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => (
|
export const getOrphanVisits = (buildShlinkApiClient: ShlinkApiClientBuilder) => createVisitsAsyncThunk({
|
||||||
{ orphanVisitsType, query = {}, doIntervalFallback = false }: LoadOrphanVisits,
|
actionsPrefix: `${REDUCER_PREFIX}/getOrphanVisits`,
|
||||||
) => async (dispatch: Dispatch, getState: GetState) => {
|
createLoaders: ({ orphanVisitsType, query = {}, doIntervalFallback = false }: LoadOrphanVisits, getState) => {
|
||||||
const { getOrphanVisits: getVisits } = buildShlinkApiClient(getState);
|
const { getOrphanVisits: getVisits } = buildShlinkApiClient(getState);
|
||||||
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits({ ...query, page, itemsPerPage })
|
const visitsLoader = async (page: number, itemsPerPage: number) => getVisits({ ...query, page, itemsPerPage })
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
const visits = result.data.filter((visit) => isOrphanVisit(visit) && matchesType(visit, orphanVisitsType));
|
const visits = result.data.filter((visit) => isOrphanVisit(visit) && matchesType(visit, orphanVisitsType));
|
||||||
|
|
||||||
return { ...result, data: visits };
|
return { ...result, data: visits };
|
||||||
});
|
});
|
||||||
const lastVisitLoader = lastVisitLoaderForLoader(doIntervalFallback, getVisits);
|
const lastVisitLoader = lastVisitLoaderForLoader(doIntervalFallback, getVisits);
|
||||||
const shouldCancel = () => getState().orphanVisits.cancelLoad;
|
|
||||||
const extraFinishActionData: Partial<VisitsLoaded> = { query };
|
|
||||||
const prefix = `${REDUCER_PREFIX}/getOrphanVisits`;
|
|
||||||
|
|
||||||
return getVisitsWithLoader(visitsLoader, lastVisitLoader, extraFinishActionData, prefix, dispatch, shouldCancel);
|
return [visitsLoader, lastVisitLoader];
|
||||||
|
},
|
||||||
|
getExtraFulfilledPayload: ({ query = {} }: LoadOrphanVisits) => ({ query }),
|
||||||
|
shouldCancel: (getState) => getState().orphanVisits.cancelLoad,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const orphanVisitsReducerCreator = (
|
||||||
|
{ asyncThunk, largeAction, progressChangedAction, fallbackToIntervalAction }: ReturnType<typeof getOrphanVisits>,
|
||||||
|
) => {
|
||||||
|
const { reducer, actions } = createSlice({
|
||||||
|
name: REDUCER_PREFIX,
|
||||||
|
initialState,
|
||||||
|
reducers: {
|
||||||
|
cancelGetOrphanVisits: (state) => ({ ...state, cancelLoad: true }),
|
||||||
|
},
|
||||||
|
extraReducers: (builder) => {
|
||||||
|
builder.addCase(asyncThunk.pending, () => ({ ...initialState, loading: true }));
|
||||||
|
builder.addCase(asyncThunk.rejected, (_, { error }) => (
|
||||||
|
{ ...initialState, error: true, errorData: parseApiError(error) }
|
||||||
|
));
|
||||||
|
builder.addCase(asyncThunk.fulfilled, (state, { payload }) => (
|
||||||
|
{ ...state, ...payload, loading: false, loadingLarge: false, error: false }
|
||||||
|
));
|
||||||
|
|
||||||
|
builder.addCase(largeAction, (state) => ({ ...state, loadingLarge: true }));
|
||||||
|
builder.addCase(progressChangedAction, (state, { payload: progress }) => ({ ...state, progress }));
|
||||||
|
builder.addCase(fallbackToIntervalAction, (state, { payload: fallbackInterval }) => (
|
||||||
|
{ ...state, fallbackInterval }
|
||||||
|
));
|
||||||
|
|
||||||
|
builder.addCase(createNewVisits, (state, { payload }: CreateVisitsAction) => {
|
||||||
|
const { visits, query = {} } = state;
|
||||||
|
const { startDate, endDate } = query;
|
||||||
|
const newVisits = payload.createdVisits
|
||||||
|
.filter(({ visit, shortUrl }) => !shortUrl && isBetween(visit.date, startDate, endDate))
|
||||||
|
.map(({ visit }) => visit);
|
||||||
|
|
||||||
|
return { ...state, visits: [...newVisits, ...visits] };
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const { cancelGetOrphanVisits } = actions;
|
||||||
|
|
||||||
|
return { reducer, cancelGetOrphanVisits };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const cancelGetOrphanVisits = createAction<void>(`${REDUCER_PREFIX}/getOrphanVisits/cancel`);
|
|
||||||
|
|
|
@ -9,7 +9,7 @@ import { NonOrphanVisits } from '../NonOrphanVisits';
|
||||||
import { cancelGetShortUrlVisits, getShortUrlVisits } from '../reducers/shortUrlVisits';
|
import { cancelGetShortUrlVisits, getShortUrlVisits } from '../reducers/shortUrlVisits';
|
||||||
import { cancelGetTagVisits, getTagVisits } from '../reducers/tagVisits';
|
import { cancelGetTagVisits, getTagVisits } from '../reducers/tagVisits';
|
||||||
import { getDomainVisits, domainVisitsReducerCreator } from '../reducers/domainVisits';
|
import { getDomainVisits, domainVisitsReducerCreator } from '../reducers/domainVisits';
|
||||||
import { cancelGetOrphanVisits, getOrphanVisits } from '../reducers/orphanVisits';
|
import { getOrphanVisits, orphanVisitsReducerCreator } from '../reducers/orphanVisits';
|
||||||
import { getNonOrphanVisits, nonOrphanVisitsReducerCreator } from '../reducers/nonOrphanVisits';
|
import { getNonOrphanVisits, nonOrphanVisitsReducerCreator } from '../reducers/nonOrphanVisits';
|
||||||
import { ConnectDecorator } from '../../container/types';
|
import { ConnectDecorator } from '../../container/types';
|
||||||
import { loadVisitsOverview, visitsOverviewReducerCreator } from '../reducers/visitsOverview';
|
import { loadVisitsOverview, visitsOverviewReducerCreator } from '../reducers/visitsOverview';
|
||||||
|
@ -64,8 +64,9 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
|
||||||
bottle.serviceFactory('getDomainVisits', prop('asyncThunk'), 'getDomainVisitsCreator');
|
bottle.serviceFactory('getDomainVisits', prop('asyncThunk'), 'getDomainVisitsCreator');
|
||||||
bottle.serviceFactory('cancelGetDomainVisits', prop('cancelGetDomainVisits'), 'domainVisitsReducerCreator');
|
bottle.serviceFactory('cancelGetDomainVisits', prop('cancelGetDomainVisits'), 'domainVisitsReducerCreator');
|
||||||
|
|
||||||
bottle.serviceFactory('getOrphanVisits', getOrphanVisits, 'buildShlinkApiClient');
|
bottle.serviceFactory('getOrphanVisitsCreator', getOrphanVisits, 'buildShlinkApiClient');
|
||||||
bottle.serviceFactory('cancelGetOrphanVisits', () => cancelGetOrphanVisits);
|
bottle.serviceFactory('getOrphanVisits', prop('asyncThunk'), 'getOrphanVisitsCreator');
|
||||||
|
bottle.serviceFactory('cancelGetOrphanVisits', prop('cancelGetOrphanVisits'), 'orphanVisitsReducerCreator');
|
||||||
|
|
||||||
bottle.serviceFactory('getNonOrphanVisitsCreator', getNonOrphanVisits, 'buildShlinkApiClient');
|
bottle.serviceFactory('getNonOrphanVisitsCreator', getNonOrphanVisits, 'buildShlinkApiClient');
|
||||||
bottle.serviceFactory('getNonOrphanVisits', prop('asyncThunk'), 'getNonOrphanVisitsCreator');
|
bottle.serviceFactory('getNonOrphanVisits', prop('asyncThunk'), 'getNonOrphanVisitsCreator');
|
||||||
|
@ -83,6 +84,9 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
|
||||||
|
|
||||||
bottle.serviceFactory('nonOrphanVisitsReducerCreator', nonOrphanVisitsReducerCreator, 'getNonOrphanVisitsCreator');
|
bottle.serviceFactory('nonOrphanVisitsReducerCreator', nonOrphanVisitsReducerCreator, 'getNonOrphanVisitsCreator');
|
||||||
bottle.serviceFactory('nonOrphanVisitsReducer', prop('reducer'), 'nonOrphanVisitsReducerCreator');
|
bottle.serviceFactory('nonOrphanVisitsReducer', prop('reducer'), 'nonOrphanVisitsReducerCreator');
|
||||||
|
|
||||||
|
bottle.serviceFactory('orphanVisitsReducerCreator', orphanVisitsReducerCreator, 'getOrphanVisitsCreator');
|
||||||
|
bottle.serviceFactory('orphanVisitsReducer', prop('reducer'), 'orphanVisitsReducerCreator');
|
||||||
};
|
};
|
||||||
|
|
||||||
export default provideServices;
|
export default provideServices;
|
||||||
|
|
|
@ -1,15 +1,8 @@
|
||||||
import { Mock } from 'ts-mockery';
|
import { Mock } from 'ts-mockery';
|
||||||
import { addDays, formatISO, subDays } from 'date-fns';
|
import { addDays, formatISO, subDays } from 'date-fns';
|
||||||
import reducer, {
|
import {
|
||||||
getOrphanVisits,
|
getOrphanVisits as getOrphanVisitsCreator,
|
||||||
cancelGetOrphanVisits,
|
orphanVisitsReducerCreator,
|
||||||
GET_ORPHAN_VISITS_START,
|
|
||||||
GET_ORPHAN_VISITS_ERROR,
|
|
||||||
GET_ORPHAN_VISITS,
|
|
||||||
GET_ORPHAN_VISITS_LARGE,
|
|
||||||
GET_ORPHAN_VISITS_CANCEL,
|
|
||||||
GET_ORPHAN_VISITS_PROGRESS_CHANGED,
|
|
||||||
GET_ORPHAN_VISITS_FALLBACK_TO_INTERVAL,
|
|
||||||
} from '../../../src/visits/reducers/orphanVisits';
|
} from '../../../src/visits/reducers/orphanVisits';
|
||||||
import { rangeOf } from '../../../src/utils/utils';
|
import { rangeOf } from '../../../src/utils/utils';
|
||||||
import { Visit } from '../../../src/visits/types';
|
import { Visit } from '../../../src/visits/types';
|
||||||
|
@ -24,34 +17,37 @@ import { VisitsInfo } from '../../../src/visits/reducers/types';
|
||||||
describe('orphanVisitsReducer', () => {
|
describe('orphanVisitsReducer', () => {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const visitsMocks = rangeOf(2, () => Mock.all<Visit>());
|
const visitsMocks = rangeOf(2, () => Mock.all<Visit>());
|
||||||
|
const getOrphanVisitsCall = jest.fn();
|
||||||
|
const buildShlinkApiClientMock = () => Mock.of<ShlinkApiClient>({ getOrphanVisits: getOrphanVisitsCall });
|
||||||
|
const creator = getOrphanVisitsCreator(buildShlinkApiClientMock);
|
||||||
|
const { asyncThunk: getOrphanVisits, largeAction, progressChangedAction, fallbackToIntervalAction } = creator;
|
||||||
|
const { reducer, cancelGetOrphanVisits } = orphanVisitsReducerCreator(creator);
|
||||||
|
|
||||||
|
beforeEach(jest.clearAllMocks);
|
||||||
|
|
||||||
describe('reducer', () => {
|
describe('reducer', () => {
|
||||||
const buildState = (data: Partial<VisitsInfo>) => Mock.of<VisitsInfo>(data);
|
const buildState = (data: Partial<VisitsInfo>) => Mock.of<VisitsInfo>(data);
|
||||||
|
|
||||||
it('returns loading on GET_ORPHAN_VISITS_START', () => {
|
it('returns loading on GET_ORPHAN_VISITS_START', () => {
|
||||||
const state = reducer(buildState({ loading: false }), { type: GET_ORPHAN_VISITS_START } as any);
|
const { loading } = reducer(buildState({ loading: false }), { type: getOrphanVisits.pending.toString() });
|
||||||
const { loading } = state;
|
|
||||||
|
|
||||||
expect(loading).toEqual(true);
|
expect(loading).toEqual(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns loadingLarge on GET_ORPHAN_VISITS_LARGE', () => {
|
it('returns loadingLarge on GET_ORPHAN_VISITS_LARGE', () => {
|
||||||
const state = reducer(buildState({ loadingLarge: false }), { type: GET_ORPHAN_VISITS_LARGE } as any);
|
const { loadingLarge } = reducer(buildState({ loadingLarge: false }), { type: largeAction.toString() });
|
||||||
const { loadingLarge } = state;
|
|
||||||
|
|
||||||
expect(loadingLarge).toEqual(true);
|
expect(loadingLarge).toEqual(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns cancelLoad on GET_ORPHAN_VISITS_CANCEL', () => {
|
it('returns cancelLoad on GET_ORPHAN_VISITS_CANCEL', () => {
|
||||||
const state = reducer(buildState({ cancelLoad: false }), { type: GET_ORPHAN_VISITS_CANCEL } as any);
|
const { cancelLoad } = reducer(buildState({ cancelLoad: false }), { type: cancelGetOrphanVisits.toString() });
|
||||||
const { cancelLoad } = state;
|
|
||||||
|
|
||||||
expect(cancelLoad).toEqual(true);
|
expect(cancelLoad).toEqual(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('stops loading and returns error on GET_ORPHAN_VISITS_ERROR', () => {
|
it('stops loading and returns error on GET_ORPHAN_VISITS_ERROR', () => {
|
||||||
const state = reducer(buildState({ loading: true, error: false }), { type: GET_ORPHAN_VISITS_ERROR } as any);
|
const { loading, error } = reducer(
|
||||||
const { loading, error } = state;
|
buildState({ loading: true, error: false }),
|
||||||
|
{ type: getOrphanVisits.rejected.toString() },
|
||||||
|
);
|
||||||
|
|
||||||
expect(loading).toEqual(false);
|
expect(loading).toEqual(false);
|
||||||
expect(error).toEqual(true);
|
expect(error).toEqual(true);
|
||||||
|
@ -59,11 +55,10 @@ describe('orphanVisitsReducer', () => {
|
||||||
|
|
||||||
it('return visits on GET_ORPHAN_VISITS', () => {
|
it('return visits on GET_ORPHAN_VISITS', () => {
|
||||||
const actionVisits = [{}, {}];
|
const actionVisits = [{}, {}];
|
||||||
const state = reducer(buildState({ loading: true, error: false }), {
|
const { loading, error, visits } = reducer(buildState({ loading: true, error: false }), {
|
||||||
type: GET_ORPHAN_VISITS,
|
type: getOrphanVisits.fulfilled.toString(),
|
||||||
payload: { visits: actionVisits },
|
payload: { visits: actionVisits },
|
||||||
} as any);
|
});
|
||||||
const { loading, error, visits } = state;
|
|
||||||
|
|
||||||
expect(loading).toEqual(false);
|
expect(loading).toEqual(false);
|
||||||
expect(error).toEqual(false);
|
expect(error).toEqual(false);
|
||||||
|
@ -109,14 +104,13 @@ describe('orphanVisitsReducer', () => {
|
||||||
const { visits } = reducer(prevState, {
|
const { visits } = reducer(prevState, {
|
||||||
type: createNewVisits.toString(),
|
type: createNewVisits.toString(),
|
||||||
payload: { createdVisits: [{ visit }, { visit }] },
|
payload: { createdVisits: [{ visit }, { visit }] },
|
||||||
} as any);
|
});
|
||||||
|
|
||||||
expect(visits).toHaveLength(expectedVisits);
|
expect(visits).toHaveLength(expectedVisits);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns new progress on GET_ORPHAN_VISITS_PROGRESS_CHANGED', () => {
|
it('returns new progress on GET_ORPHAN_VISITS_PROGRESS_CHANGED', () => {
|
||||||
const state = reducer(undefined, { type: GET_ORPHAN_VISITS_PROGRESS_CHANGED, payload: 85 } as any);
|
const state = reducer(undefined, { type: progressChangedAction.toString(), payload: 85 });
|
||||||
|
|
||||||
expect(state).toEqual(expect.objectContaining({ progress: 85 }));
|
expect(state).toEqual(expect.objectContaining({ progress: 85 }));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -124,7 +118,7 @@ describe('orphanVisitsReducer', () => {
|
||||||
const fallbackInterval: DateInterval = 'last30Days';
|
const fallbackInterval: DateInterval = 'last30Days';
|
||||||
const state = reducer(
|
const state = reducer(
|
||||||
undefined,
|
undefined,
|
||||||
{ type: GET_ORPHAN_VISITS_FALLBACK_TO_INTERVAL, payload: fallbackInterval } as any,
|
{ type: fallbackToIntervalAction.toString(), payload: fallbackInterval },
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(state).toEqual(expect.objectContaining({ fallbackInterval }));
|
expect(state).toEqual(expect.objectContaining({ fallbackInterval }));
|
||||||
|
@ -132,27 +126,24 @@ describe('orphanVisitsReducer', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('getOrphanVisits', () => {
|
describe('getOrphanVisits', () => {
|
||||||
type GetVisitsReturn = Promise<ShlinkVisits> | ((query: any) => Promise<ShlinkVisits>);
|
|
||||||
|
|
||||||
const buildApiClientMock = (returned: GetVisitsReturn) => Mock.of<ShlinkApiClient>({
|
|
||||||
getOrphanVisits: jest.fn(typeof returned === 'function' ? returned : async () => returned),
|
|
||||||
});
|
|
||||||
const dispatchMock = jest.fn();
|
const dispatchMock = jest.fn();
|
||||||
const getState = () => Mock.of<ShlinkState>({
|
const getState = () => Mock.of<ShlinkState>({
|
||||||
orphanVisits: { cancelLoad: false },
|
orphanVisits: { cancelLoad: false },
|
||||||
});
|
});
|
||||||
|
|
||||||
beforeEach(jest.resetAllMocks);
|
|
||||||
|
|
||||||
it('dispatches start and error when promise is rejected', async () => {
|
it('dispatches start and error when promise is rejected', async () => {
|
||||||
const ShlinkApiClient = buildApiClientMock(Promise.reject({}));
|
getOrphanVisitsCall.mockRejectedValue({});
|
||||||
|
|
||||||
await getOrphanVisits(() => ShlinkApiClient)({})(dispatchMock, getState);
|
await getOrphanVisits({})(dispatchMock, getState, {});
|
||||||
|
|
||||||
expect(dispatchMock).toHaveBeenCalledTimes(2);
|
expect(dispatchMock).toHaveBeenCalledTimes(2);
|
||||||
expect(dispatchMock).toHaveBeenNthCalledWith(1, { type: GET_ORPHAN_VISITS_START });
|
expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
|
||||||
expect(dispatchMock).toHaveBeenNthCalledWith(2, { type: GET_ORPHAN_VISITS_ERROR });
|
type: getOrphanVisits.pending.toString(),
|
||||||
expect(ShlinkApiClient.getOrphanVisits).toHaveBeenCalledTimes(1);
|
}));
|
||||||
|
expect(dispatchMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
|
||||||
|
type: getOrphanVisits.rejected.toString(),
|
||||||
|
}));
|
||||||
|
expect(getOrphanVisitsCall).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
|
@ -160,37 +151,45 @@ describe('orphanVisitsReducer', () => {
|
||||||
[{}],
|
[{}],
|
||||||
])('dispatches start and success when promise is resolved', async (query) => {
|
])('dispatches start and success when promise is resolved', async (query) => {
|
||||||
const visits = visitsMocks.map((visit) => ({ ...visit, visitedUrl: '' }));
|
const visits = visitsMocks.map((visit) => ({ ...visit, visitedUrl: '' }));
|
||||||
const ShlinkApiClient = buildApiClientMock(Promise.resolve({
|
getOrphanVisitsCall.mockResolvedValue({
|
||||||
data: visits,
|
data: visits,
|
||||||
pagination: {
|
pagination: {
|
||||||
currentPage: 1,
|
currentPage: 1,
|
||||||
pagesCount: 1,
|
pagesCount: 1,
|
||||||
totalItems: 1,
|
totalItems: 1,
|
||||||
},
|
},
|
||||||
}));
|
});
|
||||||
|
|
||||||
await getOrphanVisits(() => ShlinkApiClient)({ query })(dispatchMock, getState);
|
await getOrphanVisits({ query })(dispatchMock, getState, {});
|
||||||
|
|
||||||
expect(dispatchMock).toHaveBeenCalledTimes(2);
|
expect(dispatchMock).toHaveBeenCalledTimes(2);
|
||||||
expect(dispatchMock).toHaveBeenNthCalledWith(1, { type: GET_ORPHAN_VISITS_START });
|
expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
|
||||||
expect(dispatchMock).toHaveBeenNthCalledWith(2, {
|
type: getOrphanVisits.pending.toString(),
|
||||||
type: GET_ORPHAN_VISITS,
|
}));
|
||||||
|
expect(dispatchMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
|
||||||
|
type: getOrphanVisits.fulfilled.toString(),
|
||||||
payload: { visits, query: query ?? {} },
|
payload: { visits, query: query ?? {} },
|
||||||
});
|
}));
|
||||||
expect(ShlinkApiClient.getOrphanVisits).toHaveBeenCalledTimes(1);
|
expect(getOrphanVisitsCall).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
[
|
[
|
||||||
[Mock.of<Visit>({ date: formatISO(subDays(new Date(), 5)) })],
|
[Mock.of<Visit>({ date: formatISO(subDays(new Date(), 5)) })],
|
||||||
{ type: GET_ORPHAN_VISITS_FALLBACK_TO_INTERVAL, payload: 'last7Days' },
|
{ type: fallbackToIntervalAction.toString(), payload: 'last7Days' },
|
||||||
|
3,
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
[Mock.of<Visit>({ date: formatISO(subDays(new Date(), 200)) })],
|
[Mock.of<Visit>({ date: formatISO(subDays(new Date(), 200)) })],
|
||||||
{ type: GET_ORPHAN_VISITS_FALLBACK_TO_INTERVAL, payload: 'last365Days' },
|
{ type: fallbackToIntervalAction.toString(), payload: 'last365Days' },
|
||||||
|
3,
|
||||||
],
|
],
|
||||||
[[], expect.objectContaining({ type: GET_ORPHAN_VISITS })],
|
[[], expect.objectContaining({ type: getOrphanVisits.fulfilled.toString() }), 2],
|
||||||
])('dispatches fallback interval when the list of visits is empty', async (lastVisits, expectedSecondDispatch) => {
|
])('dispatches fallback interval when the list of visits is empty', async (
|
||||||
|
lastVisits,
|
||||||
|
expectedSecondDispatch,
|
||||||
|
expectedDispatchCalls,
|
||||||
|
) => {
|
||||||
const buildVisitsResult = (data: Visit[] = []): ShlinkVisits => ({
|
const buildVisitsResult = (data: Visit[] = []): ShlinkVisits => ({
|
||||||
data,
|
data,
|
||||||
pagination: {
|
pagination: {
|
||||||
|
@ -199,22 +198,23 @@ describe('orphanVisitsReducer', () => {
|
||||||
totalItems: 1,
|
totalItems: 1,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const getShlinkOrphanVisits = jest.fn()
|
getOrphanVisitsCall
|
||||||
.mockResolvedValueOnce(buildVisitsResult())
|
.mockResolvedValueOnce(buildVisitsResult())
|
||||||
.mockResolvedValueOnce(buildVisitsResult(lastVisits));
|
.mockResolvedValueOnce(buildVisitsResult(lastVisits));
|
||||||
const ShlinkApiClient = Mock.of<ShlinkApiClient>({ getOrphanVisits: getShlinkOrphanVisits });
|
|
||||||
|
|
||||||
await getOrphanVisits(() => ShlinkApiClient)({ doIntervalFallback: true })(dispatchMock, getState);
|
await getOrphanVisits({ doIntervalFallback: true })(dispatchMock, getState, {});
|
||||||
|
|
||||||
expect(dispatchMock).toHaveBeenCalledTimes(2);
|
expect(dispatchMock).toHaveBeenCalledTimes(expectedDispatchCalls);
|
||||||
expect(dispatchMock).toHaveBeenNthCalledWith(1, { type: GET_ORPHAN_VISITS_START });
|
expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
|
||||||
|
type: getOrphanVisits.pending.toString(),
|
||||||
|
}));
|
||||||
expect(dispatchMock).toHaveBeenNthCalledWith(2, expectedSecondDispatch);
|
expect(dispatchMock).toHaveBeenNthCalledWith(2, expectedSecondDispatch);
|
||||||
expect(getShlinkOrphanVisits).toHaveBeenCalledTimes(2);
|
expect(getOrphanVisitsCall).toHaveBeenCalledTimes(2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('cancelGetOrphanVisits', () => {
|
describe('cancelGetOrphanVisits', () => {
|
||||||
it('just returns the action with proper type', () =>
|
it('just returns the action with proper type', () =>
|
||||||
expect(cancelGetOrphanVisits()).toEqual({ type: GET_ORPHAN_VISITS_CANCEL }));
|
expect(cancelGetOrphanVisits()).toEqual({ type: cancelGetOrphanVisits.toString() }));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in a new issue