How to getSelectors through passing arg in endpoint.select() in Redux RTK - react-redux

I currently have this piece of code.
const initialState = documentsAdapter.getInitialState()
export const setupsApiSlice = apiSlice.injectEndpoints({
tagTypes: ['Setup'],
endpoints: builder => ({
getSetups: builder.query({
query: (documentId) => ({
url: `/documents/${documentId}/setups`,
method: 'GET'
}),
providesTags: ['Setup']
}),
})
})
export const {
useGetSetupsQuery,
useAddSetupsMutation,
useUpdateSetupsMutation,
useDeleteSetupsMutation
} = apiSlice
And now I want to make use of the of the getSelector and do something like this (not implemented).
export const selectSetupsResult = setupsApiSlice.endpoints.getSetups.select()
// Creates memoized selector
const selectSetupsData = createSelector(
selectSetupsResult,
setupsResult => setupsResult.data // normalized state object with ids & entities
)
export const {
selectAll: selectAllSetups,
selectById: selectSetupById,
selectIds: selectSetupIds,
} = setupsAdapter.getSelectors(state => selectSetupsData(state) ?? initialState)
The problem that I encounter is that endpoint.select() needs an argument in my case so that I can call setups on the correct documentId. I know I could just call all the setups and then filter out the ones that have the same documentId, but I was wondering if there is any other way. Even if it means not calling the endpoints.select() and still being able to use the getSelectors().

const initialState = documentsAdapter.getInitialState()
export const setupsApiSlice = apiSlice.injectEndpoints({
tagTypes: ['Setup'],
endpoints: builder => ({
getSetups: builder.query({
query: (documentId) => ({
url: `/documents/${documentId}/setups`,
method: 'GET'
}),
// Add transformResponse
transformResponse: (responseData) => {
return documentsAdapter.setAll(initialState, responseData)
},
providesTags: ['Setup']
}),
})
})
// Define function to get selectors based on arguments (query) of getSetups
export const getSelectors = (
query,
) => {
const selectSetupsResult = setupsApiSlice.endpoints.getSetups.select(query)
const adapterSelectors = createSelector(
selectSetupsResult,
(result) => documentsAdapter.getSelectors(() => result?.data ?? initialState)
)
return {
selectAll: createSelector(adapterSelectors, (s) =>
s.selectAll(undefined)
),
selectEntities: createSelector(adapterSelectors, (s) =>
s.selectEntities(undefined)
),
selectIds: createSelector(adapterSelectors, (s) =>
s.selectIds(undefined)
),
selectTotal: createSelector(adapterSelectors, (s) =>
s.selectTotal(undefined)
),
selectById: (id) => createSelector(adapterSelectors, (s) =>
s.selectById(s, id)
),
}
}
Then you can use it in a component as:
const { isFetching } = useGetSetupsQuery({id: 1})
// Dinamically get selectors based on parent query
const { selectAll: selectAllFromId1, selectById: selectByIdFromId1 } = getSelectors({id: 1})
// Use selectors based on parent id 1
const allFromId1 = useSelector(selectAllFromId1)
const setup1fromId1 = useSelector(selectByIdFromId1(5)) // get id 5

Related

Redux RTK reloading state when calling getSelectors

I am new to Redux RTK so the problem might not exactly be on calling getSelectors(). However, when I'm using the state that comes from getSelectors() it reloads the entire state.
Problem
The baseline is that I have different Setup objects that I'm calling based on the documentId. These Setup objects are quite large so in the getSetups I am only fetching some basic properties. Then, when the user selects a specific Setup from the dropdown I want to save it in the setupSlice. But when I trigger the dispatch(setSetup(data)) the RTK reloads all the Setups.
I encounter an infinite loop when after fetching all the Setup objects I want to automatically assign the default Setup to the setupSlice.
Extra
Ideally when I assign a Setup to the setupSlice I would like to call the getSetup from RTK to fetch the entire Setup object of that specific Setup and store it in the setupSlice.
I am not sure if this is suppose to be happening but is there anyway to stop it? Otherwise is there any recommendation so I can move forward?
This is the component I'm trying to generate:
const SetupDropdown = () => {
const dispatch = useDispatch()
const { documentId } = useParams()
const { data, isFetching } = useGetSetupsQuery({ documentId })
let setupsMenu;
const { selectAll: selectAllSetups } = getSelectors({documentId})
const allSetups = useSelector(selectAllSetups)
if (!isFetching) {
const defaultSetup = allSetups.find((setup) => setup.default)
setupsMenu = allSetups.map(setup => {
return (<MenuItem value={setup.id}>{setup.name}</MenuItem>)
})
dispatch(setSetup(defaultSetup))
}
const setupId = useSelector(selectSetupId)
const handleChange = async (event) => {
// Here I ideally call the getSetup RTK Query to fetch the entire information of the single setup
const data = {
id: event.target.value,
name: 'Random name'
}
dispatch(setSetup(data))
};
return (
<FormControl sx={{ minWidth: 200 }} size="small">
<InputLabel>Setup</InputLabel>
<Select
value={setupId}
onChange={handleChange}
label="Setup"
>
{setupsMenu}
</Select>
</FormControl>
)
}
export default SetupDropdown;
This is the setupApiSlice:
const setupsAdapter = createEntityAdapter({
sortComparer: (a, b) => b.date.localeCompare(a.date)
})
const initialState = setupsAdapter.getInitialState()
export const setupsApiSlice = apiSlice.injectEndpoints({
tagTypes: ['Setup'],
endpoints: builder => ({
getSetups: builder.query({
query: ({ documentId }) => ({
url: `/documents/${documentId}/setups`,
method: 'GET'
}),
transformResponse: responseData => {
return setupsAdapter.setAll(initialState, responseData)
},
providesTags: (result, error, arg) => [
{ type: 'Setup', id: "LIST" },
...result.ids.map(id => ({ type: 'Setup', id }))
]
}),
getSetup: builder.query({
query: ({ documentId, setupId }) => ({
url: `/documents/${documentId}/setups/${setupId}`,
method: 'GET'
})
})
})
})
export const {
useGetSetupsQuery,
useGetSetupQuery
} = setupsApiSlice
// Define function to get selectors based on arguments (query) of getSetups
export const getSelectors = (
query,
) => {
const selectSetupsResult = setupsApiSlice.endpoints.getSetups.select(query)
const adapterSelectors = createSelector(
selectSetupsResult,
(result) => setupsAdapter.getSelectors(() => result?.data ?? initialState)
)
return {
selectAll: createSelector(adapterSelectors, (s) =>
s.selectAll(undefined)
),
selectEntities: createSelector(adapterSelectors, (s) =>
s.selectEntities(undefined)
),
selectIds: createSelector(adapterSelectors, (s) =>
s.selectIds(undefined)
),
selectTotal: createSelector(adapterSelectors, (s) =>
s.selectTotal(undefined)
),
selectById: (id) => createSelector(adapterSelectors, (s) =>
s.selectById(s, id)
),
}
}
This is the setupSplice:
const initialState = {
name: null,
filters: [],
data: {},
status: 'idle', //'idle' | 'loading' | 'succeeded' | 'failed'
error: null
}
const setupSlice = createSlice({
name: 'setup',
initialState,
reducers: {
setSetup: (state, action) => {
console.log('Dispatch')
const setup = action.payload;
console.log(setup)
state.id = setup.id;
state.name = setup.name;
state.filters = setup.filters;
state.data = setup.state;
state.status = 'succeeded';
}
}
})
export const { setSetup } = setupSlice.actions;
export const selectSetupId = (state) => state.setup.id;
export const selectSetupName = (state) => state.setup.name;
export const selectSetupFilters = (state) => state.setup.filters;
export const selectSetupData = (state) => state.setup.data;
export default setupSlice.reducer;
Tbh., you probably should be using selectFromResult in your useGetSetupsQuery instead of adding another useSelector hook. That would also reduce your code complexity by a lot.
Your problem as hand is that you are creating those selectors within your component on each render - so they don't have a chance to actually memoize and give you a stable result. If you do that in your component, wrap it in a useMemo call to keep your selector instances as stable as possible.

How to mock useRouter parameters for react-hooks-testing-library?

I have a custom hook, which has structure of:
const urlHook = () => {
const router = useRouter();
const read = () => {
return validate(router.query.param);
}
const write = (params) => {
router.push(
{
query: {
param: params,
},
},
undefined,
{shallow: true},
)
}
const validate = (params) => {}
}
I want to test this hook using react-hooks-testing-library but I'm not sure how to setup for router.query.param to read values that I want or how to check if function write() will create correct url?
To mock entire hook - jest.requireActual:
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({
blogId: 'company1',
articleId: 'blog1',
}),
useRouteMatch: () => ({ url: '/blog/blog1/article/article1' }),
}));
To mock history/routing state - MemoryRouter:
import {Route, MemoryRouter} from 'react-router-dom';
...
const renderWithRouter = ({children}) => (
render(
<MemoryRouter initialEntries={['blogs/1']}>
<Route path='blogs/:blogId'>
{children}
</Route>
</MemoryRouter>
)
)
Helpful example with explanations:
https://v5.reactrouter.com/web/guides/testing

selector returning different value despite custom equalityFn check returning true

I have the following selector and effect
const filterValues = useSelector<State, string[]>(
state => state.filters.filter(f => f.field === variableId).map(f => f.value),
(left, right) => {
return left.length === right.length && left.every(l => right.includes(l));
},
);
const [value, setValue] = useState<SelectionRange>({ start: null, end: null });
useEffect(() => {
const values = filterValues
.filter(av => av).sort((v1, v2) => v1.localeCompare(v2));
const newValue = {
start: values[0] ?? null,
end: values[1] ?? null,
};
setValue(newValue);
}, [filterValues]);
the selector above initially returns an empty array, but a different one every time and I don't understand why because the equality function should guarantee it doesn't.
That makes the effect trigger, sets the state, the selector runs again (normal) but returns another different empty array! causing the code to run in an endless cycle.
Why is the selector returning a different array each time? what am I missing?
I am using react-redux 7.2.2
react-redux e-runs the selector if the selector is a new reference, because it assumes the code could have changed what it's selecting entirely
https://github.com/reduxjs/react-redux/issues/1654
one solution is to memoize the selector function
const selector = useMemo(() => (state: State) => state.filters.filter(f => f.field === variableId).map(f => f.value), [variableId]);
const filterValues = useSelector<State, string[]>(
selector ,
(left, right) => {
return left.length === right.length && left.every(l => right.includes(l));
},
);
You can try memoizing the result of your filter in a selector and calculate value in a selector as well, now I'm not sure if you still need the local state of value as it's just a copy of a derived value from redux state and only causes an extra render when you copy it but here is the code:
const { Provider, useDispatch, useSelector } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;
const { createSelector, defaultMemoize } = Reselect;
const { useState, useEffect, useMemo } = React;
const initialState = {
filters: [
{ field: 1, value: 1 },
{ field: 2, value: 2 },
{ field: 1, value: 3 },
{ field: 2, value: 4 },
],
};
//action types
const TOGGLE = 'NEW_STATE';
const NONE = 'NONE';
//action creators
const toggle = () => ({
type: TOGGLE,
});
const none = () => ({ type: NONE });
const reducer = (state, { type }) => {
if (type === TOGGLE) {
return {
filters: state.filters.map((f) =>
f.field === 1
? { ...f, field: 2 }
: { ...f, field: 1 }
),
};
}
if (type === NONE) {
//create filters again should re run selector
// but not re render
return {
filters: [...state.filters],
};
}
return state;
};
//selectors
const selectFilters = (state) => state.filters;
const createSelectByVariableId = (variableId) => {
const memoArray = defaultMemoize((...args) => args);
return createSelector([selectFilters], (filters) =>
memoArray.apply(
null,
filters
.filter((f) => f.field === variableId)
.map((f) => f.value)
)
);
};
const createSelectSelectValue = (variableId) =>
createSelector(
[createSelectByVariableId(variableId)],
//?? does not work in SO because babel is too old
(values) => ({
start: values[0] || null,
end: values[1] || null,
})
);
//creating store with redux dev tools
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducer,
initialState,
composeEnhancers(
applyMiddleware(() => (next) => (action) =>
next(action)
)
)
);
var last;
const App = ({ variableId }) => {
const selectValue = useMemo(
() => createSelectSelectValue(variableId),
[variableId]
);
const reduxValue = useSelector(selectValue);
if (last !== reduxValue) {
console.log('not same', last, reduxValue);
last = reduxValue;
}
//not sure if you still need this, you are just
// copying a value you already have
const [value, setValue] = useState(reduxValue);
const dispatch = useDispatch();
useEffect(() => setValue(reduxValue), [reduxValue]);
console.log('rendering...', value);
return (
<div>
<button onClick={() => dispatch(toggle())}>
toggle
</button>
<button onClick={() => dispatch(none())}>none</button>
<pre>{JSON.stringify(value, undefined, 2)}</pre>
</div>
);
};
ReactDOM.render(
<Provider store={store}>
<App variableId={1} />
</Provider>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>
<div id="root"></div>

Redux Observable - How to send off an action to start a separate epic, then wait for that epics response (or timeout)

So I basically have a websocket connection, this allows me to send generic messages via WEBSOCKET_MESSAGE_SEND and receive them via WEBSOCKET_MESSAGE_RECEIVED actions.
However there are cases where I want to make a request in a similar manner to a Ajax REST call. Eg to request a list of documents for a user I probably want to have an epic:
Receive an action eg ({ type: GET_DOCUMENTS })
Generate a random key to track the current request, we will call it 'request_id'
Send a ({ type: WEBSOCKET_MESSAGE_SEND, request_id }) action.
Wait for either of
an action ({ type: WEBSOCKET_MESSAGE_RECEIVED, request_id, message }) **Must be with a matching 'request_id' otherwise it should be ignored.
-> Emit an action eg ({ type: GET_DOCUMENTS_SUCCESS, documents: message })
a timeout eg 10 seconds
-> Emit an action eg ({ type: GET_DOCUMENTS_TIMEOUT })
I have been struggling to put this into code, I think the most awkward part of the whole epic is that I want to emit an action in the middle of my epic and wait. This doesn't feel quite right to me... ani-pattern? But I am not really sure how I should be doing this.
That's right. There is no good way to emit an action in the middle of an epic. How about splitting the epic into two?
const getDocumentsEpic = action$ =>
action$.pipe(
ofType("GET_DOCUMENTS"),
map(() => {
const requestId = generateRequestId();
return {
type: "WEBSOCKET_MESSAGE_SEND",
requestId
};
})
);
const websocketMessageEpic = action$ =>
action$.pipe(
ofType("WEBSOCKET_MESSAGE_SEND"),
switchMap(requestId => {
return action$.pipe(
ofType("WEBSOCKET_MESSAGE_RECEIVED"),
filter(action => action.requestId === requestId),
timeout(10000),
map(({ message }) => ({
type: "GET_DOCUMENTS_SUCCESS",
documents: message
})),
catchError(() => of({ type: "GET_DOCUMENTS_TIMEOUT" }))
);
})
);
Updated answer (2020-04-17):
I was unhappy with my original answer so decided to give it another shot.
NotificationOperators.js
import { of } from 'rxjs';
import { map, switchMap, filter, timeout, catchError, first, mergeMap } from 'rxjs/operators';
import { notificationActionTypes } from '../actions';
const NOTIFICATION_TIMEOUT = 60 * 1000;
const generateRequestId = () => Math.random().toString(16).slice(2);
const toNotificationRequest = notificationRequest => input$ =>
input$.pipe(mergeMap(async action => ({
type: notificationActionTypes.WEBSOCKET_MESSAGE_SEND,
message: {
request_id: generateRequestId(),
...(
typeof notificationRequest === "function" ?
await Promise.resolve(notificationRequest(action)) :
({ eventType: notificationRequest })
)
}
})));
const mapNotificationRequestResponses = (notificationRequest, mapper) => $input =>
$input.pipe(
filter(action =>
action.type === notificationActionTypes.WEBSOCKET_MESSAGE_SEND &&
action.message.eventType === notificationRequest),
concatMap(sendAction =>
$input.pipe(
filter(receiveAction => {
return (
receiveAction.type === notificationActionTypes.WEBSOCKET_MESSAGE_RECEIVED &&
receiveAction.message.request_id === sendAction.message.request_id
)
}),
first(),
timeout(NOTIFICATION_TIMEOUT),
map(({ message }) => mapper(message.success ? false : message.error, message.result, sendAction.message)),
catchError(errorMessage => of(mapper(errorMessage && errorMessage.message, null, sendAction.message))))));
export { toNotificationRequest, mapNotificationRequestResponses };
Usage:
export const getDocumentsReqEpic = action$ => action$.pipe(
ofType(documentActionTypes.REFRESH_DOCUMENTS_REQUEST),
toNotificationRequest(EventTypes.get_user_documents_req)
);
export const getDocumentsRecEpic = action$ => action$.pipe(
mapNotificationRequestResponses(
EventTypes.get_user_documents_req,
(error, result) => error ? refreshDocumentsError(error) : refreshDocumentsSuccess(result))
);
Original answer:
As I felt I would likely need to repeat this process many more times, this seemed like a reasonable amount of duplicated boilterplate that I should create a method to generate epics based on requirements. For this reason I have expanded upon #sneas awesome answer and have posted below incase it helps others.
Note this implementation assumes the websocket implementation from the other answer. It also assumes that the server websocket implementation will accept a 'request_id' and respond with the same 'request_id' so that request and response messages can be linked. Probably also worth noting that the 'epicLinkId' is client-side only, and simply enables the 2 epics being created to be linked to each other, without this you would only be able to call createNotifyReqResEpics() once.
createNotifyReqResEpics.js (helper based on code above)
import { ofType } from 'redux-observable';
import { of } from 'rxjs';
import { map, switchMap, filter, timeout, catchError, first } from 'rxjs/operators';
import { notificationActionTypes } from '../actions';
const generateRequestId = () => Math.random().toString(16).slice(2);
export default ({
requestFilter,
requestMessageMapper,
responseMessageMapper
}) => {
if (typeof requestFilter !== "function")
throw new Error("Invalid function passed into createNotifyReqResEpics 'requestFilter' argument.");
if (typeof requestMessageMapper !== "function")
throw new Error("Invalid function passed into createNotifyReqResEpics 'requestMessageMapper' argument.");
if (typeof responseMessageMapper !== "function")
throw new Error("Invalid function passed into createNotifyReqResEpics 'responseMessageMapper' argument.");
const epicLinkId = generateRequestId();
const websocketSendEpic = action$ =>
action$.pipe(
filter(requestFilter),
map(action => ({
epic_link_id: epicLinkId,
type: notificationActionTypes.WEBSOCKET_MESSAGE_SEND,
message: {
request_id: generateRequestId(),
...requestMessageMapper(action)
}
}))
);
const websocketReceiveEpic = action$ =>
action$.pipe(
ofType(notificationActionTypes.WEBSOCKET_MESSAGE_SEND),
filter(action => action.epic_link_id === epicLinkId),
switchMap(sendAction =>
action$.pipe(
ofType(notificationActionTypes.WEBSOCKET_MESSAGE_RECEIVED),
filter(receiveAction => receiveAction.request_id === sendAction.request_id),
first(),
timeout(10000),
map(receiveAction => responseMessageMapper(false, receiveAction.message)),
catchError(errorMessage => of(responseMessageMapper(errorMessage && errorMessage.message, null))))));
return [websocketSendEpic, websocketReceiveEpic];
};
documents.js (epics)
import EventTypes from '../shared-dependencies/EventTypes';
import { documentActionTypes, refreshDocumentsError, refreshDocumentsSuccess } from '../actions';
import { createNotifyReqResEpics } from '../utils';
const [getDocumentsReqEpic, getDocumentsRespEpic] = createNotifyReqResEpics({
requestFilter: action => action.type === documentActionTypes.REFRESH_DOCUMENTS_REQUEST,
requestMessageMapper: action => ({ eventType: EventTypes.get_user_documents_req }),
responseMessageMapper: (error, action) => error ? refreshDocumentsError(error) : refreshDocumentsSuccess(action.result)
});
export { getDocumentsReqEpic, getDocumentsRespEpic };
Where the 2 exported epics from documents.js make thie way into combineEpics.

How can I test Observable.ajax (redux-observable)?

I have been playing with rxjs and redux-observable for the last few days and have been struggle to find a way to a test for Observable.ajax. I have the following epic which create a request to https://jsonplaceholder.typicode.com/,
export function testApiEpic (action$) {
return action$.ofType(REQUEST)
.switchMap(action =>
Observable.ajax({ url, method })
.map(data => successTestApi(data.response))
.catch(error => failureTestApi(error))
.takeUntil(action$.ofType(CLEAR))
)
}
where,
export const REQUEST = 'my-app/testApi/REQUEST'
export const SUCCESS = 'my-app/testApi/SUCCESS'
export const FAILURE = 'my-app/testApi/FAILURE'
export const CLEAR = 'my-app/testApi/CLEAR'
export function requestTestApi () {
return { type: REQUEST }
}
export function successTestApi (response) {
return { type: SUCCESS, response }
}
export function failureTestApi (error) {
return { type: FAILURE, error }
}
export function clearTestApi () {
return { type: CLEAR }
}
The code works fine when runs in browser but not when testing with Jest.
I have try,
1) Create a test based on https://redux-observable.js.org/docs/recipes/WritingTests.html. The store.getActions() returns only { type: REQUEST }.
const epicMiddleware = createEpicMiddleware(testApiEpic)
const mockStore = configureMockStore([epicMiddleware])
describe.only('fetchUserEpic', () => {
let store
beforeEach(() => {
store = mockStore()
})
afterEach(() => {
epicMiddleware.replaceEpic(testApiEpic)
})
it('returns a response, () => {
store.dispatch({ type: REQUEST })
expect(store.getActions()).toEqual([
{ type: REQUEST },
{ type: SUCCESS, response }
])
})
})
2) Create a test based on Redux-observable: failed jest test for epic. It returns with
Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
it('returns a response', (done) => {
const action$ = ActionsObservable.of({ type: REQUEST })
const store = { getState: () => {} }
testApiEpic(action$, store)
.toArray()
.subscribe(actions => {
expect(actions).to.deep.equal([
{ type: SUCCESS, response }
])
done()
})
})
Can someone point me out what is the correct way to test Observable.ajax ?
I would follow the second example, from StackOverflow. To make it work you'll need to make some minor adjustments. Instead of importing Observable.ajax in your epic file and using that reference directly, you need to use some form of dependency injection. One way is to provide it to the middleware when you create it.
import { ajax } from 'rxjs/observable/dom/ajax';
const epicMiddleware = createEpicMiddleware(rootEpic, {
dependencies: { ajax }
});
The object we passed as dependencies will be give to all epics as the third argument
export function testApiEpic (action$, store, { ajax }) {
return action$.ofType(REQUEST)
.switchMap(action =>
ajax({ url, method })
.map(data => successTestApi(data.response))
.catch(error => failureTestApi(error))
.takeUntil(action$.ofType(CLEAR))
);
}
Alternatively, you could not use the dependencies option of the middleware and instead just use default parameters:
export function testApiEpic (action$, store, ajax = Observable.ajax) {
return action$.ofType(REQUEST)
.switchMap(action =>
ajax({ url, method })
.map(data => successTestApi(data.response))
.catch(error => failureTestApi(error))
.takeUntil(action$.ofType(CLEAR))
);
}
Either one you choose, when we test the epic we can now call it directly and provide our own mock for it. Here are examples for success/error/cancel paths These are untested and might have issues, but should give you the general idea
it('handles success path', (done) => {
const action$ = ActionsObservable.of(requestTestApi())
const store = null; // not used by epic
const dependencies = {
ajax: (url, method) => Observable.of({ url, method })
};
testApiEpic(action$, store, dependencies)
.toArray()
.subscribe(actions => {
expect(actions).to.deep.equal([
successTestApi({ url: '/whatever-it-is', method: 'WHATEVERITIS' })
])
done();
});
});
it('handles error path', (done) => {
const action$ = ActionsObservable.of(requestTestApi())
const store = null; // not used by epic
const dependencies = {
ajax: (url, method) => Observable.throw({ url, method })
};
testApiEpic(action$, store, dependencies)
.toArray()
.subscribe(actions => {
expect(actions).to.deep.equal([
failureTestApi({ url: '/whatever-it-is', method: 'WHATEVERITIS' })
])
done();
});
});
it('supports cancellation', (done) => {
const action$ = ActionsObservable.of(requestTestApi(), clearTestApi())
const store = null; // not used by epic
const dependencies = {
ajax: (url, method) => Observable.of({ url, method }).delay(100)
};
const onNext = chai.spy();
testApiEpic(action$, store, dependencies)
.toArray()
.subscribe({
next: onNext,
complete: () => {
onNext.should.not.have.been.called();
done();
}
});
});
For the first way:
First, use isomorphic-fetch instead of Observable.ajax for nock support, like this
const fetchSomeData = (api: string, params: FetchDataParams) => {
const request = fetch(`${api}?${stringify(params)}`)
.then(res => res.json());
return Observable.from(request);
};
So my epic is:
const fetchDataEpic: Epic<GateAction, ImGateState> = action$ =>
action$
.ofType(FETCH_MODEL)
.mergeMap((action: FetchModel) =>
fetchDynamicData(action.url, action.params)
.map((payload: FetchedData) => fetchModelSucc(payload.data))
.catch(error => Observable.of(
fetchModelFail(error)
)));
Then, you may need an interval to decide when to finish the test.
describe("epics", () => {
let store: MockStore<{}>;
beforeEach(() => {
store = mockStore();
});
afterEach(() => {
nock.cleanAll();
epicMiddleware.replaceEpic(epic);
});
it("fetch data model succ", () => {
const payload = {
code: 0,
data: someData,
header: {},
msg: "ok"
};
const params = {
data1: 100,
data2: "4"
};
const mock = nock("https://test.com")
.get("/test")
.query(params)
.reply(200, payload);
const go = new Promise((resolve) => {
store.dispatch({
type: FETCH_MODEL,
url: "https://test.com/test",
params
});
let interval: number;
interval = window.setInterval(() => {
if (mock.isDone()) {
clearInterval(interval);
resolve(store.getActions());
}
}, 20);
});
return expect(go).resolves.toEqual([
{
type: FETCH_MODEL,
url: "https://test.com/assignment",
params
},
{
type: FETCH_MODEL_SUCC,
data: somData
}
]);
});
});
enjoy it :)

Resources