redux-mock-store icon indicating copy to clipboard operation
redux-mock-store copied to clipboard

Test with extra dispatched action in middleware

Open Cicko opened this issue 6 years ago • 0 comments

Hi coders! I would like to test my middleware and in my case I use it to check if an input field value has correct pattern to display an error in case of not.

My ValidationMiddleware.js:

import { FORM_SET_VALUE, FORM_SET_ERROR } from '../../../lib/components/containers/form/store/constants';

const validationMiddleware = store => next => action => {
	if (action.type !== FORM_SET_VALUE) {
		return next(action);
	}
	const { pattern, value, attr } = action;
	const state = store.getState();
	const newError = new RegExp(pattern).exec(value) === null;
	const oldError = state.form.form[attr] ? state.form.form[attr].error : false;
	if (newError !== oldError) {
		store.dispatch({
			type: FORM_SET_ERROR,
			error: newError,
			attr,
		});
	}
	next(action);
};

export default validationMiddleware; 

And my ValidationMiddleware.text.js:

const configureMockStore = require('redux-mock-store').default;
import validationMiddleware from './validationMiddleware';
import { FORM_SET_ERROR } from '../../../lib/components/containers/form/store/constants';
import { setFormValue } from '../../../lib/components/containers/form/store/actions';

const mockStore = configureMockStore([validationMiddleware]);

describe('Validation middleware', () => {
	it('should dispatch error when wrong value for specific pattern', () => {

		const store = mockStore({
			form: {
				form: {
					field: {
						error: false,
					},
				},
			},
		});
		store.dispatch(setFormValue('field', '123', '^[a-zA-Z\-\'. ]*$'));
		const expectedPayload = {
			type: FORM_SET_ERROR,
			attr: 'field',
			error: true,
		};
		const actions = store.getActions();
		expect(actions).toEqual([expectedPayload]);
	});
});

The point is that it dispatches another action in case of error so there are two different actions dispatched instead of one (FORM_SET_ERROR and FORM_SET_VALUE).

So I don't know how to check if the FORM_SET_ERROR was dispatched. Any ideas?

Thank you in advance!

Cicko avatar Sep 22 '19 12:09 Cicko