score:3
Accepted answer
here is the unit test solution:
api.middleware.ts
:
import { middleware } from 'redux';
import axios from 'axios';
import { api_request } from './actiontypes';
import { apisuccess, apierror } from './actioncreator';
export const apimiddleware: middleware = ({ dispatch }) => (next) => async (action): promise<void> => {
next(action);
if (action.type.includes(api_request)) {
const body = action.payload;
const { url, method, feature } = action.meta;
try {
const response = await axios({ method, url, data: body });
dispatch(apisuccess({ response, feature }));
} catch (error) {
console.error(error);
dispatch(apierror({ error, feature }));
}
}
};
actiontypes.ts
:
export const api_request = 'api_request';
export const api_request_success = 'api_request_success';
export const api_request_failure = 'api_request_failure';
actioncreator.ts
:
import { api_request_success, api_request_failure } from './actiontypes';
export function apisuccess(data) {
return {
type: api_request_success,
...data,
};
}
export function apierror(data) {
return {
type: api_request_failure,
...data,
};
}
api.middleware.test.ts
:
import { apimiddleware } from './api.middleware';
import axios from 'axios';
import { middlewareapi } from 'redux';
import { api_request, api_request_success, api_request_failure } from './actiontypes';
jest.mock('axios', () => jest.fn());
describe('59754838', () => {
aftereach(() => {
jest.clearallmocks();
});
describe('#apimiddleware', () => {
describe('unit test', () => {
it('should dispatch api success action', async () => {
const store: middlewareapi = { dispatch: jest.fn(), getstate: jest.fn() };
const next = jest.fn();
const action = {
type: api_request,
payload: {},
meta: { url: 'http://localhost', method: 'get', feature: 'feature' },
};
const mresponse = { name: 'user name' };
(axios as jest.mocked<any>).mockresolvedvalueonce(mresponse);
await apimiddleware(store)(next)(action);
expect(next).tobecalledwith(action);
expect(axios).tobecalledwith({ method: action.meta.method, url: action.meta.url, data: action.payload });
expect(store.dispatch).tobecalledwith({
type: api_request_success,
response: mresponse,
feature: action.meta.feature,
});
});
it('should dispatch api error action', async () => {
const store: middlewareapi = { dispatch: jest.fn(), getstate: jest.fn() };
const next = jest.fn();
const action = {
type: api_request,
payload: {},
meta: { url: 'http://localhost', method: 'get', feature: 'feature' },
};
const merror = new error('network error');
(axios as jest.mocked<any>).mockrejectedvalueonce(merror);
await apimiddleware(store)(next)(action);
expect(next).tobecalledwith(action);
expect(axios).tobecalledwith({ method: action.meta.method, url: action.meta.url, data: action.payload });
expect(store.dispatch).tobecalledwith({
type: api_request_failure,
error: merror,
feature: action.meta.feature,
});
});
});
});
});
unit test results with coverage report:
pass src/stackoverflow/59754838/api.middleware.test.ts (11.206s)
59754838
#apimiddleware
unit test
✓ should dispatch api success action (21ms)
✓ should dispatch api error action (23ms)
console.error src/stackoverflow/59754838/api.middleware.ts:3460
error: network error
at /users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59754838/api.middleware.test.ts:42:24
at step (/users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59754838/api.middleware.test.ts:33:23)
at object.next (/users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59754838/api.middleware.test.ts:14:53)
at /users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59754838/api.middleware.test.ts:8:71
at new promise (<anonymous>)
at object.<anonymous>.__awaiter (/users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59754838/api.middleware.test.ts:4:12)
at object.<anonymous> (/users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/59754838/api.middleware.test.ts:34:46)
at object.asyncjesttest (/users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/jasmineasyncinstall.js:102:37)
at resolve (/users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queuerunner.js:43:12)
at new promise (<anonymous>)
at mapper (/users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queuerunner.js:26:19)
at promise.then (/users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queuerunner.js:73:41)
at process._tickcallback (internal/process/next_tick.js:68:7)
-------------------|----------|----------|----------|----------|-------------------|
file | % stmts | % branch | % funcs | % lines | uncovered line #s |
-------------------|----------|----------|----------|----------|-------------------|
all files | 100 | 50 | 100 | 100 | |
actioncreator.ts | 100 | 100 | 100 | 100 | |
actiontypes.ts | 100 | 100 | 100 | 100 | |
api.middleware.ts | 100 | 50 | 100 | 100 | 9 |
-------------------|----------|----------|----------|----------|-------------------|
test suites: 1 passed, 1 total
tests: 2 passed, 2 total
snapshots: 0 total
time: 12.901s
source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59754838
Source: stackoverflow.com
Related Query
- Testing a Redux & Axios fetch middleware with Jest
- Testing dispatched actions in Redux thunk with Jest
- How to test redux state update with react testing library and jest
- Redux testing multipart/form-data with jest, nock, axios and jsdom
- Getting undefined with jest mock testing axios
- Having trouble Jest testing ajax modules with axios
- Testing a component's state after an async fetch with Jest & Enzyme (using module)
- Testing async behavior in React with Axios and Jest
- Testing fetch request with Jest and Enzyme
- Testing a React Hooks component with Jest / Enzyme & Axios
- Testing a React component with Jest / Enzyme & Axios
- Unit Testing redux async function with Jest
- Post Data With Redux and Fetch API with Axios Get Error Result so Looping Response Pending
- Unit testing react redux thunk dispatches with jest and react testing library for "v: 16.13.1",
- How to Create Middleware for refresh token in Reactjs with axios and redux
- Unit Testing with Jest and React - Axios Get Inside useEffect
- Jest testing with axios call
- Testing double axios request with jest in react app
- Testing a Redux connected component with enzyme and jest
- How to test a className with the Jest and React testing library
- Testing with Jest and Webpack aliases
- Testing React Functional Component with Hooks using Jest
- Shared utils functions for testing with Jest
- Handling api calls in Redux with Axios
- Nested components testing with Enzyme inside of React & Redux
- Jest "No tests found, exiting with code 1" error on Windows 10 in React Redux application
- Cannot read property '.then' of undefined when testing async action creators with redux and react
- How to mock out sub-components when unit testing a React component with Jest
- Testing with React's Jest and Enzyme when simulated clicks call a function that calls a promise
- Testing with React's Jest and Enzyme when async componentDidMount
More Query from same tag
- React state resets with Socket.io
- response.map() is not a function in reactjs
- Tag Error: React JSX Style Tag Error on Render
- fetch data is providing some [assets] and [objects]. How can I de-structure these in the following code in order to list them out?
- How to show a table on hovering a button in react?
- How do I get the value of Radio button(react-radio-buttons) in Reactjs?
- Ant Design- autocomplete need to not show value
- React - onmouseenter doesn't work between child elements
- react-dates datepicker default popup behaviour
- catch is not invoked on moxios reject
- Gatsby theme i18n markdown doesn't change language when toggle
- React usestate components only show on change
- How to pass multiple properties down 2 levels of components while keeping their names in React?
- Check react input form for decimals and change value
- Docker + Nodejs + Brunch + ReactJS image
- Filter API Data Based on Array Of Strings
- Method not updating state when called in componentDidMount()
- How can I use HTML5 Validation with React?
- Trying to use Bootstrap Nav Pills in React Router's NavLink
- filter api data in reactjs
- How to correctly assign axios response to react function component state
- How do I change the number of cards displayed in row
- Accepting Decimal values within input
- React useEffect and mousedown listener
- How to overlay a React component over a scrollable div?
- Turn an array of React context providers into a nested structure
- Passing number as props in React becomes Object object
- Reactjs Render issue on popover with data fetched from BE
- how to type component using css emotion?
- Reactjs and Mongodb connection