diff --git a/src/servers/reducers/remoteServers.ts b/src/servers/reducers/remoteServers.ts index 52e1bc9f..8f5083a8 100644 --- a/src/servers/reducers/remoteServers.ts +++ b/src/servers/reducers/remoteServers.ts @@ -1,18 +1,21 @@ import { pipe, prop } from 'ramda'; import { AxiosInstance } from 'axios'; -import { Dispatch } from 'redux'; import pack from '../../../package.json'; import { hasServerData, ServerData } from '../data'; import { createServers } from './servers'; +import { createAsyncThunk } from '../../utils/helpers/redux'; const responseToServersList = pipe( prop('data'), (data: any): ServerData[] => (Array.isArray(data) ? data.filter(hasServerData) : []), ); -export const fetchServers = ({ get }: AxiosInstance) => () => async (dispatch: Dispatch) => { - const resp = await get(`${pack.homepage}/servers.json`); - const remoteList = responseToServersList(resp); +export const fetchServers = ({ get }: AxiosInstance) => createAsyncThunk( + 'shlink/remoteServers/fetchServers', + async (_: void, { dispatch }): Promise => { + const resp = await get(`${pack.homepage}/servers.json`); + const result = responseToServersList(resp); - dispatch(createServers(remoteList)); -}; + dispatch(createServers(result)); + }, +); diff --git a/test/servers/reducers/remoteServers.test.ts b/test/servers/reducers/remoteServers.test.ts index 708e2905..41e19238 100644 --- a/test/servers/reducers/remoteServers.test.ts +++ b/test/servers/reducers/remoteServers.test.ts @@ -7,9 +7,9 @@ describe('remoteServersReducer', () => { afterEach(jest.clearAllMocks); describe('fetchServers', () => { + const dispatch = jest.fn(); const get = jest.fn(); const axios = Mock.of({ get }); - const dispatch = jest.fn(); it.each([ [ @@ -84,10 +84,17 @@ describe('remoteServersReducer', () => { [{}, {}], ])('tries to fetch servers from remote', async (mockedValue, expectedNewServers) => { get.mockResolvedValue(mockedValue); + const doFetchServers = fetchServers(axios); - await fetchServers(axios)()(dispatch); + await doFetchServers()(dispatch, jest.fn(), {}); - expect(dispatch).toHaveBeenCalledWith({ type: createServers.toString(), payload: expectedNewServers }); + expect(dispatch).toHaveBeenNthCalledWith(1, expect.objectContaining({ + type: doFetchServers.pending.toString(), + })); + expect(dispatch).toHaveBeenNthCalledWith(2, { type: createServers.toString(), payload: expectedNewServers }); + expect(dispatch).toHaveBeenNthCalledWith(3, expect.objectContaining({ + type: doFetchServers.fulfilled.toString(), + })); expect(get).toHaveBeenCalledTimes(1); }); });