Unit Testing Redux Feature Flag Functionality
Present a code example for unit testing the functionality related to a Redux feature flag, including actions, reducers, and selectors.
import { createStore } from 'redux';
import { expect } from 'chai';
// Feature flag related actions
const UPDATE_FEATURE_FLAG = 'UPDATE_FEATURE_FLAG';
const updateFeatureFlag = (flag, value) => ({
type: UPDATE_FEATURE_FLAG,
payload: { flag, value }
});
// Feature flag reducer
const initialFeatureFlagsState = {};
const featureFlagsReducer = (state = initialFeatureFlagsState, action) => {
switch (action.type) {
case UPDATE_FEATURE_FLAG:
return {
...state,
[action.payload.flag]: action.payload.value
};
default:
return state;
}
};
// Feature flag selector
const getFeatureFlag = (state, flag) => state[flag];
// Unit test for the reducer and action
describe('Feature flags reducer and actions', () => {
it('should update a feature flag value', () => {
const store = createStore(featureFlagsReducer);
const flagName = 'newFeature';
const flagValue = true;
store.dispatch(updateFeatureFlag(flagName, flagValue));
expect(store.getState()[flagName]).to.equal(flagValue);
});
});
// Unit test for the selector
describe('Feature flag selector', () => {
it('should select feature flag value', () => {
const state = { newFeature: true };
const flagValue = getFeatureFlag(state, 'newFeature');
expect(flagValue).to.be.true;
});
});
This JSON object contains three snippets of JavaScript code for unit testing Redux feature flag functionality. The first snippet defines Redux actions and a reducer for updating feature flags. The second snippet uses Chai to test the action and reducer logic through a store dispatch. The third snippet is a simple test for the selector function that retrieves the value of a specified feature flag from the state.