The Redux Documentation declares Jest as the unit testing framework of choice. This is a beginners introduction to Jest.
Taken from the Jest documentation:
Zero configuration – Jest is already configured when you use
create-react-app
orreact-native init
to create your React and React Native projects. Place your tests in a__tests__
folder, or name your test files with a.spec.js
or.test.js
extension. Whatever you prefer, Jest will find and run your tests.
As it turns out, Jest is already integrated into your codebase should you have used create-react-app.
Error fsevents unavailable
When npm run
fails with the following output:
npm test > cryptofrontend@0.1.0 test /Users/bischowg/dev/react/cryptofrontend > react-scripts test Error: `fsevents` unavailable (this watcher can only be used on Darwin) at new FSEventsWatcher (/Users/bischowg/dev/react/cryptofrontend/node_modules/sane/src/fsevents_watcher.js:41:11) at createWatcher (/Users/bischowg/dev/react/cryptofrontend/node_modules/jest-haste-map/build/index.js:780:23) at Array.map (<anonymous>) at HasteMap._watch (/Users/bischowg/dev/react/cryptofrontend/node_modules/jest-haste-map/build/index.js:936:44) at _buildPromise._buildFileMap.then.then.hasteMap (/Users/bischowg/dev/react/cryptofrontend/node_modules/jest-haste-map/build/index.js:355:23) at <anonymous> at process._tickCallback (internal/process/next_tick.js:160:7) npm ERR! Test failed. See above for more details.
read https://github.com/expo/expo/issues/854
npm r -g watchman
brew install watchman
I had to run the brew command three times before it finally worked. npm test should now work without issues.
Testing Action Creators
Given a file actions.js that contains the action creator
function receiveEntriesActionCreator(json) { return { type: RECEIVE_ENTRIES, entries: json } }
you want to write a test that verifies that the action creator returns an action that has a type property with a value of RECEIVE_ENTRIES and an entries property that contains a specific javascript object.
In order to write the test, add a file called actions.test.js next to actions.js. In actions.test.js insert:
import * as actions from './actions.js'; import { RECEIVE_ENTRIES, ADD_ENTRY, UPDATE_ENTRY, DELETE_ENTRY } from './actions.js' test('receiveEntriesActionCreator returns a correct action', () => { const entries = [{ id: '12345', password: 'abcdef' }] const expectedAction = { type: RECEIVE_ENTRIES, entries } expect(actions.receiveEntriesActionCreator(entries)).toEqual(expectedAction) });
On line 10, the test() function is called given a description of what the test is trying to verify. The second parameter is the code that the test should execute. Lines 12 to 17 assemble the expected result. On line 19, expect().toEqual() is called.
In the console type npm run
to start a watcher that executes the tests after you save your changes to a file that has a unit test.