react-redux-test-utils
Utils for testing react-redux applications using enzyme and jest snapshots
Why
- It separates between unit-testing and integration-testing and gives you tools to write both.
- It reduces the boilerplate.
- It uses a data-driven approach for unit-testing so instead of writing test logic, you define objects that describe your tests.
- It is very fast and easy to write tests.
- It comes with enzyme and uses snapshots testing.
Installation
# with npm
npm install --save-dev react-redux-test-utils
# with yarn
yarn add -D react-redux-test-utils
Usage
react-redux-test-utils
allow you to write unit-testing that look like this:
/* UserProfile.test.js */
import { testComponentSnapshotsWithFixtures } from 'react-redux-test-utils';
import UserProfile from '../UserProfile';
const fixtures = {
'should render UserProfile': {
user: 'some-user',
},
'should render UserProfile with avatar': {
user: 'some-user',
showAvatar: true,
},
'should render UserProfile with posts and photos': {
user: 'some-user',
showPosts: true,
showPhotos: true,
},
};
describe('UserProfile - component', () =>
testComponentSnapshotsWithFixtures(UserProfile, fixtures));
It also provide the IntegrationTestHelper
that helps with writing integration-testing:
/* __tests__/integration.test.js */
import React from 'react';
import { IntegrationTestHelper } from 'react-redux-test-utils';
import UserProfile, { reducers } from '../index';
describe('UserProfile - Integration Test', () => {
it('should flow', () => {
const integrationTestHelper = new IntegrationTestHelper(reducers);
const component = integrationTestHelper.mount(
<UserProfile user="some-user" />
);
// The user-avatar should not be shown
expect(component.exists('UserAvatar')).toEqual(false);
integrationTestHelper.takeStoreSnapshot('initial state');
// trigger checkbox change
component
.find('input#show-avatar-toggler')
.simulate('change', { target: { checked: true } });
// The user-avatar should be shown now
expect(component.exists('UserAvatar')).toEqual(true);
integrationTestHelper.takeStoreAndLastActionSnapshot(
'Update to show the user-avatar'
);
});
});
Documentations
- Manage your folder structure.
- Unit-testing components.
- Unit-testing redux actions.
- Unit-testing redux reducers.
- Unit-testing redux selectors.
- Integration-testing.
Related
- generator-react-domain will help you to generate react components with domain-driven file structuring and with tests file that uses the
react-redux-test-utils
.
License
MIT © Avi Sharvit
Manage your code folder structure
Before we can start unit testing our components, we need to adopt an approach when we export 2 versions of the same component, one connected to redux and one unconnected.
With this approach, we will manage our code folder structure by domain level, and we will create small independent and connected mini-packages. We will write integration-testing with full redux-flow for our connected component/min-package, and unit-testing for unconnected components, actions, reducers, selectors, helpers, and co...
Folder tree
src
├── components
│ └── UserProfile
│ ├── index.js // integration-file/connected-component
│ ├── UserProfile.js // main component
│ ├── UserProfileActions.js
│ ├── UserProfileConstants.js
│ ├── UserProfileReducer.js
│ ├── UserProfileSelectors.js
│ ├── __tests__ // test files
│ │ ├── integration.test.js // integration-test
│ │ ├── UserProfile.test.js
│ │ ├── UserProfileActions.test.js
│ │ ├── UserProfileReducer.test.js
│ │ └── UserProfileSelectors.test.js
│ └── components // inner components
│ ├── UserAvatar.js
│ ├── UserAvatar.test.js
│ ├── UserPosts.js
│ └── UserPosts.test.js
└── store
└── index.js
./manual/
The main unconnected component
Learn how to write unit-testing for your unconnected components.
/* UserProfile.js */
import React from 'react';
import UserAvatar from './components/UserAvatar';
import UserDetailsBox from './components/UserDetailsBox';
import UserPhotos from './components/UserPhotos';
import UserPosts from './components/UserPosts';
const UserProfile = ({
user,
showAvatar,
showPosts,
showPhotos,
updateShowAvatar,
updateShowPhotos,
updateShowPosts,
}) => (
<div className="user-profile">
<UserDetailsBox user={user} />
{showAvatar && <UserAvatar user={user} size="sm" />}
{showPosts && <UserPhotos user={user} count={5} sort="DESC" />}
{showPhotos && <UserPosts user={user} count={5} sort="DESC" />}
<input
id="show-avatar-toggler"
type="checkbox"
checked={showAvatar}
onChange={e => updateShowAvatar(e.target.checked)}
/>
<input
id="show-photos-toggler"
type="checkbox"
checked={showPhotos}
onChange={e => updateShowPhotos(e.target.checked)}
/>
<input
id="show-posts-toggler"
type="checkbox"
checked={showPosts}
onChange={e => updateShowPosts(e.target.checked)}
/>
</div>
);
export default UserProfile;
./manual/
The integration file
Learn how to write integration-testing for your connected components.
/* index.js */
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actions from './UserProfileActions';
import reducer from './UserProfileReducer';
import {
selectShowAvatar,
selectShowPosts,
selectShowPhotos,
} from './UserProfileSelectors';
import UserProfile from './UserProfile';
// map state to props
const mapStateToProps = state => ({
showAvatar: selectShowAvatar(state),
showPosts: selectShowPosts(state),
showPhotos: selectShowPhotos(state),
});
// map action dispatchers to props
const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);
// export reducers
export const reducers = { userProfile: reducer };
// export connected component
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserProfile);
./manual/
Use generators
generator-react-domain is a recommended generator that will help you to generate react components with domain-driven file structuring and with tests file that uses the react-redux-test-utils
.
Next: Learn how to write unit-testing for your unconnected components ->
Testing components
Before we can start unit testing our components, we need to adopt an approach when we export 2 versions of the same component, ./manual/one connected to redux and one unconnected.
Learn how to manage your code folder structure
Component example
/* UserProfile.js */
const UserProfile = ({
user,
showAvatar,
showPosts,
showPhotos,
updateShowAvatar,
updateShowPhotos,
updateShowPosts,
}) => (
<div className="user-profile">
<UserDetailsBox user={user} />
{showAvatar && <UserAvatar user={user} size="sm" />}
{showPosts && <UserPhotos user={user} count={5} sort="DESC" />}
{showPhotos && <UserPosts user={user} count={5} sort="DESC" />}
<input
id="show-avatar-toggler"
type="checkbox"
checked={showAvatar}
onChange={e => updateShowAvatar(e.target.checked)}
/>
<input
id="show-photos-toggler"
type="checkbox"
checked={showPhotos}
onChange={e => updateShowPhotos(e.target.checked)}
/>
<input
id="show-posts-toggler"
type="checkbox"
checked={showPosts}
onChange={e => updateShowPosts(e.target.checked)}
/>
</div>
);
Unit testing
/* UserProfile.test.js */
import { testComponentSnapshotsWithFixtures } from 'react-redux-test-utils';
import UserProfile from '../UserProfile';
const fixtures = {
'should render UserProfile': {
user: 'some-user',
},
'should render UserProfile with avatar': {
user: 'some-user',
showAvatar: true,
},
'should render UserProfile with posts and photos': {
user: 'some-user',
showPosts: true,
showPhotos: true,
},
};
describe('UserProfile - component', () =>
testComponentSnapshotsWithFixtures(UserProfile, fixtures));
./manual/
Testing actions
Testing regular actions
Regular actions are simple actions that return a single object.
Assuming we have this UserProfileActions.js
:
/* UserProfileActions.js */
export const updateShowAvatar = showAvatar => ({
type: USER_PROFILE_UPDATE_AVATAR,
payload: showAvatar,
});
export const updateShowPosts = showPosts => ({
type: USER_PROFILE_UPDATE_POSTS,
payload: showPosts,
});
export const updateShowPhotos = showPhotos => ({
type: USER_PROFILE_UPDATE_PHOTOS,
payload: showPhotos,
});
Testing this file should be as easy as running those functions and saving the results as a snapshot.
testActionSnapshotWithFixtures
will run over the fixtures and will save each results snapshot.
/* UserProfileActions.test.js */
import { testActionSnapshotWithFixtures } from 'react-redux-test-utils';
import {
updateShowAvatar,
updateShowPosts,
updateShowPhotos,
} from '../UserProfileActions';
const fixtures = {
'should update-show-avatar': () => updateShowAvatar(true),
'should update-show-posts': () => updateShowPosts(true),
'should update-show-photos': () => updateShowPhotos(true),
};
describe('UserProfile - Actions', () =>
testActionSnapshotWithFixtures(fixtures));
The end results will be similar to:
import { testActionSnapshotWithFixtures } from 'react-redux-test-utils';
import {
updateShowAvatar,
updateShowPosts,
updateShowPhotos,
} from '../UserProfileActions';
describe('UserProfile - Actions', () => {
test('should update-show-avatar', () => {
const results = updateShowAvatar(true);
expect(results).toMatchSnapshot();
});
test('should update-show-posts', () => {
const results = updateShowPosts(true);
expect(results).toMatchSnapshot();
});
test('should update-show-photos', () => {
const results = updateShowPhotos(true);
expect(results).toMatchSnapshot();
});
});
Testing thunk async actions
Async thunk doesn't return a simple object. Instead, they return an async function that receives a dispatch function as an argument. Assuming we have the following action:
import api from '../common/api';
export const login = ({ username, password }) => async dispatch => {
try {
dispatch({
type: 'LOGIN_REQUEST',
payload: { username, password },
});
const results = await api.post('/login', { username, password });
dispatch({
type: 'LOGIN_SUCCEED',
payload: { results },
});
} catch (error) {
dispatch({
type: 'LOGIN_ERROR',
payload: { error },
});
}
};
import { testActionSnapshotWithFixtures } from 'react-redux-test-utils';
import api from '../common/api';
import { login } from './loginActions';
jest.mock('../common/api');
describe('Login Actions', () => {
const correctLogin = { username: 'some-username', password: 'some-password' };
const wrongLogin = {
username: 'some-wrong-username',
password: 'some-wrong-password',
};
api.login.mockImplementation(async credentials =>
credentials === correctLogin
? 'succees'
: throw new Error('wrong email and password')
);
testActionSnapshotWithFixtures({
'should login and succeed': login(correctLogin),
'should login and fail': login(wrongLogin),
});
});
./manual/
Unit testing reducers
/* LoginFormReducer.js */
import {
LOGIN_FORM_UPDATE_USERNAME,
LOGIN_FORM_UPDATE_PASSWORD,
LOGIN_FORM_TOGGLE_REMEMBER_ME,
} from '../LoginFormConstants';
const initialState = Immutable({
username: '',
password: '',
rememberMe: false,
});
export default (state = initialState, action) => {
const { payload } = action;
switch (action.type) {
case LOGIN_FORM_UPDATE_USERNAME:
return state.set('username', payload);
case LOGIN_FORM_UPDATE_PASSWORD:
return state.set('password', payload);
case LOGIN_FORM_TOGGLE_REMEMBER_ME:
return state.set('rememberMe', !state.rememberMe);
default:
return state;
}
};
/* LoginFormReducer.test.js */
import { testReducerSnapshotWithFixtures } from 'react-redux-test-utils';
import {
LOGIN_FORM_UPDATE_USERNAME,
LOGIN_FORM_UPDATE_PASSWORD,
LOGIN_FORM_TOGGLE_REMEMBER_ME,
} from '../LoginFormConstants';
import reducer from '../LoginFormReducer';
const fixtures = {
'it should update username': {
action: {
type: LOGIN_FORM_UPDATE_USERNAME,
payload: { username: 'some-username' }
}
},
'it should update password': {
action: {
type: LOGIN_FORM_UPDATE_PASSWORD,
payload: { password: 'some-password' }
}
},
'it should toggle remember-me': {
state: { rememberMe: false },
action: {
type: LOGIN_FORM_TOGGLE_REMEMBER_ME,
}
},
};
describe('LoginForm - Reducer', () =>
testReducerSnapshotWithFixtures(reducer, fixtures));
./manual/
Unit testing selectors
Selectors file
/* UserProfileSelectors.js */
const selectState = state => state.userProfile;
export const selectShowAvatar = state => selectState(state).showAvatar;
export const selectShowPosts = state => selectState(state).showPosts;
export const selectShowPhotos = state => selectState(state).showPhotos;
Unit testing file
/* UserProfileSelectors.test.js */
import { testSelectorsSnapshotWithFixtures } from 'react-redux-test-utils';
import {
selectShowAvatar,
selectShowPosts,
selectShowPhotos,
} from '../UserProfileSelectors';
const state = {
userProfile: {
showAvatar: 'showAvatar',
showPosts: 'showPosts',
showPhotos: 'showPhotos',
},
};
const fixtures = {
'should select show-avatar': () => selectShowAvatar(state),
'should select show-posts': () => selectShowPosts(state),
'should select show-photos': () => selectShowPhotos(state),
};
describe('UserProfile - Selectors', () =>
testSelectorsSnapshotWithFixtures(fixtures));
./manual/
Integration testing
Integration testing should test the connected-component while activating full redux lifecycle.
Integration file
/* index.js */
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actions from './UserProfileActions';
import reducer from './UserProfileReducer';
import {
selectShowAvatar,
selectShowPosts,
selectShowPhotos,
} from './UserProfileSelectors';
import UserProfile from './UserProfile';
// map state to props
const mapStateToProps = state => ({
showAvatar: selectShowAvatar(state),
showPosts: selectShowPosts(state),
showPhotos: selectShowPhotos(state),
});
// map action dispatchers to props
const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);
// export reducers
export const reducers = { userProfile: reducer };
// export connected component
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserProfile);
Integration test file
/* __tests__/integration.test.js */
import React from 'react';
import { IntegrationTestHelper } from 'react-redux-test-utils';
import UserProfile, { reducers } from '../index';
describe('UserProfile - Integration Test', () => {
it('should flow', () => {
const integrationTestHelper = new IntegrationTestHelper(reducers);
const component = integrationTestHelper.mount(
<UserProfile user="some-user" />
);
// The user-avatar should not be shown
expect(component.exists('UserAvatar')).toEqual(false);
integrationTestHelper.takeStoreSnapshot('initial state');
// trigger checkbox change
component
.find('input#show-avatar-toggler')
.simulate('change', { target: { checked: true } });
// The user-avatar should be shown now
expect(component.exists('UserAvatar')).toEqual(true);
integrationTestHelper.takeStoreAndLastActionSnapshot(
'Update to show the user-avatar'
);
});
});
Contributing
Contributions are always welcome, no matter how large or small.
Working on your first Pull Request? You can learn how from this free series How to Contribute to an Open Source Project on GitHub
Code of Conduct
By participating, you are expected to uphold this Contributor Covenant Code of Conduct. Please report unacceptable behavior to sharvita@gmail.com.
Project setup
First, fork then clone the repo:
git clone https://github.com/your-username/react-redux-test-utils
cd react-redux-test-utils
git remote add upstream https://github.com/sharvit/react-redux-test-utils
Install dependencies:
yarn
Run test suits to validate the project is working:
yarn test
Run linter to validate the project code:
yarn lint
# to fix linting errors
yarn lint --fix
# lint your last committed message
yarn lint:commit
Build
Build src with babel:
yarn build
Documentations
Build documentation with esdocs to ./htmldocs
yarn build:docs
To develop docs, you can watch and build automatically:
yarn build:docs:dev
Committing and Pushing changes
Create a branch and start hacking:
git checkout -b my-branch
./manual/
Commit and push your changes:
generator-node.htmll
uses commitizen to create commit messages so semantic-release can automatically create releases.
git add .
yarn commit
# answer the questions
git push origin my-branch
./manual/
Open this project on GitHub, then click “Compare & pull request”.
Help needed
Please checkout the roadmap.html
and the open issues.
Also, please watch the repo and respond to questions/bug reports/feature requests, Thanks!
Contributor Covenant Code of Conduct
Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
Our Standards
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others‘ private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at sharvita@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project‘s leadership.
Attribution
This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at http://contributor-covenant.org/version/1/4
Project Roadmap
This is where we‘ll define a few things about the library‘s goals.
We haven‘t filled this out yet though. Care to help? See contributing.html