├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── examples ├── .eslintrc ├── browser-basic │ ├── .gitignore │ ├── README.md │ ├── package.json │ ├── public │ │ ├── favicon.ico │ │ └── index.html │ ├── src │ │ ├── App.css │ │ ├── App.js │ │ ├── App.logic.js │ │ ├── App.reducer.js │ │ ├── App.test.js │ │ ├── index.css │ │ ├── index.js │ │ ├── logo.svg │ │ └── store.js │ └── yarn.lock ├── buildAll.js ├── fullBuildAll.js └── nodejs-basic │ ├── index.js │ └── package.json ├── package-lock.json ├── package.json ├── src ├── createMockStore.js └── index.js ├── test ├── .eslintrc ├── createMockStore.spec.js └── setup.js └── webpack.config.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | ["transform-es2015-template-literals", { "loose": true }], 4 | "transform-es2015-literals", 5 | "transform-es2015-function-name", 6 | "transform-es2015-arrow-functions", 7 | "transform-es2015-block-scoped-functions", 8 | ["transform-es2015-classes", { "loose": true }], 9 | "transform-es2015-object-super", 10 | "transform-es2015-shorthand-properties", 11 | ["transform-es2015-computed-properties", { "loose": true }], 12 | ["transform-es2015-for-of", { "loose": true }], 13 | "transform-es2015-sticky-regex", 14 | "transform-es2015-unicode-regex", 15 | "check-es2015-constants", 16 | ["transform-es2015-spread", { "loose": true }], 17 | "transform-es2015-parameters", 18 | ["transform-es2015-destructuring", { "loose": true }], 19 | "transform-es2015-block-scoping", 20 | "transform-object-rest-spread", 21 | "transform-es3-member-expression-literals", 22 | "transform-es3-property-literals" 23 | ], 24 | "env": { 25 | "commonjs": { 26 | "plugins": [ 27 | ["transform-es2015-modules-commonjs", { "loose": true }] 28 | ] 29 | }, 30 | "es": { 31 | "plugins": [ 32 | ] 33 | }, 34 | "test": { 35 | "plugins": [ 36 | ["transform-es2015-modules-commonjs", { "loose": true }] 37 | ] 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain 2 | # consistent coding styles between different editors and IDEs. 3 | 4 | root = true 5 | 6 | [*] 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | indent_style = space 12 | indent_size = 2 13 | 14 | [*.md] 15 | trim_trailing_whitespace = false 16 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | **/dist/** 2 | **/build-es/** 3 | **/build-lib/** 4 | **/coverage/** 5 | **/node_modules/** 6 | **/server.js 7 | **/webpack.config*.js 8 | **/examples/** 9 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | /* Also check test/.eslintrc for test specific config */ 3 | "extends": "airbnb-base", 4 | "rules": { 5 | "arrow-body-style": [1, "as-needed"], 6 | "arrow-parens": 0, 7 | // don't require dangling commas 8 | "comma-dangle": 0, 9 | "consistent-return": 1, 10 | // causing issues with codacy 11 | "import/no-unresolved": 0, 12 | "indent": 0, 13 | "no-nested-ternary": 0, 14 | "no-plusplus": 0, 15 | "no-shadow": 0, 16 | // don't require functions to be declared before use 17 | "no-use-before-define": [2, { "functions": false, "classes": true }], 18 | // Disable until Flow supports let and const 19 | "no-var": 0, 20 | "object-property-newline": 0, 21 | "padded-blocks": 0, 22 | "valid-jsdoc": 2 23 | }, 24 | "parserOptions": { 25 | "ecmaFeatures": { 26 | "experimentalObjectRestSpread": true 27 | } 28 | }, 29 | "plugins": [ 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.log 3 | .nyc_output 4 | node_modules 5 | dist 6 | build-lib 7 | build-es 8 | coverage 9 | _book 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "6" 4 | - "8" 5 | - "10" 6 | - node 7 | script: 8 | - npm run check:src 9 | - npm run build 10 | - npm run build:examples 11 | branches: 12 | except: 13 | - experimental 14 | cache: 15 | directories: 16 | - $HOME/.npm 17 | - examples/browser-basic/node_modules 18 | - examples/nodejs-basic/node_modules 19 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | This project adheres to [Semantic Versioning](http://semver.org/). 4 | Every release, along with the migration instructions, is documented on the Github [Releases](https://github.com/jeffbski/redux-logic-test/releases) page. 5 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Jeff Barczewski 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # redux-logic-test - redux-logic test utilities 2 | 3 | > "Simplifying testing with redux-logic" 4 | 5 | Utilities: 6 | 7 | - `createMockStore` - create a redux-logic middleware and a redux store, attaching the middleware and providing a mechanism to verify the dispatched actions 8 | 9 | [![Build Status](https://secure.travis-ci.org/jeffbski/redux-logic-test.png?branch=master)](http://travis-ci.org/jeffbski/redux-logic-test) [![Known Vulnerabilities](https://snyk.io/test/github/jeffbski/redux-logic-test/badge.svg)](https://snyk.io/test/github/jeffbski/redux-logic-test) [![NPM Version Badge](https://img.shields.io/npm/v/redux-logic-test.svg)](https://www.npmjs.com/package/redux-logic-test) 10 | 11 | ## Installation 12 | 13 | redux-logic-test has peerDependencies of redux and redux-logic (which also needs rxjs) 14 | 15 | ```bash 16 | npm install rxjs --save 17 | npm install redux-logic --save 18 | npm install redux --save 19 | npm install redux-logic-test --save-dev 20 | ``` 21 | 22 | ### ES6 module import 23 | 24 | ```js 25 | import { createMockStore } from 'redux-logic-test'; 26 | ``` 27 | 28 | ### Commonjs 29 | 30 | ```js 31 | const createMockStore = require('redux-logic-test').default.createMockStore; 32 | ``` 33 | 34 | ### UMD/CDN use from script tags 35 | 36 | The UMD build is mainly used for using in online playgrounds like jsfiddle. 37 | 38 | ```html 39 | 40 | 41 | 42 | 47 | ``` 48 | 49 | ## Usage 50 | 51 | ```js 52 | import { createMockStore } from 'redux-logic-test'; 53 | 54 | // specify as much as necessary for your particular test 55 | const store = createMockStore({ 56 | initialState: optionalObject, 57 | reducer: optionalFn, // default: identity reducer 58 | logic: optionalLogic, // default: [] 59 | injectedDeps: optionalObject, // default {} 60 | middleware: optionalArr // other mw, exclude logicMiddleware 61 | }); 62 | 63 | store.dispatch(...) // use as necessary for your test 64 | 65 | // when all inflight logic has all completed calls fn + returns promise 66 | store.whenComplete(fn) - shorthand for store.logicMiddleware.whenComplete(fn) 67 | 68 | store.actions - the actions dispatched, use store.resetActions() to clear 69 | store.resetActions() - clear store.actions 70 | 71 | // access the logicMiddleware created for logic/injectedDeps props 72 | // use addLogic, mergeNewLogic, replaceLogic, whenComplete, monitor$ 73 | store.logicMiddleware 74 | ``` 75 | 76 | ## Goals 77 | 78 | - simplify the creation of a testing redux store with logicMiddleware attached 79 | - add built-in middleware to track actions that are dispatched 80 | - make it easy to verify the actions that were dispatched 81 | 82 | ## Quick example 83 | 84 | ```js 85 | import { createMockStore } from 'redux-logic-test'; 86 | import { createLogic } from 'redux-logic'; 87 | 88 | const fooLogic = createLogic({ 89 | type: 'FOO', 90 | process({ API, getState, action }, dispatch, done) { 91 | API.get(...) 92 | .then(results => { 93 | dispatch({ type: 'FOO_SUCCESS', payload: results }); 94 | done(); 95 | }); 96 | } 97 | }); 98 | 99 | const logic = [fooLogic]; // array of logic to use/test 100 | const injectedDeps = { // include what is needed for logic 101 | API: api // could include mocked API for easy testing 102 | }; 103 | 104 | const initialState = {}; // optionally set 105 | const reducer = (state, action) => { return state; }; // optional 106 | 107 | const store = createMockStore({ 108 | initialState, 109 | reducer, 110 | logic, 111 | injectedDeps 112 | }); 113 | 114 | store.dispatch({ type: 'FOO' }); // kick off fetching 115 | store.dispatch({ type: 'BAR' }); // other dispatches 116 | store.whenComplete(() => { // runs this fn when all logic is complete 117 | expect(store.getState()).toEqual({...}); 118 | expect(store.actions).toEqual([ 119 | { type: 'FOO' }, 120 | { type: 'BAR' }, 121 | { type: 'FOO_SUCCESS', payload: [...] } 122 | ]); 123 | // if desired, can reset the actions for more tests 124 | // store.resetActions(); // clear for more tests 125 | 126 | // be sure to return the whenComplete promise to your test 127 | // or if using a done cb, call it to indicate that your async 128 | // test is finished 129 | }); 130 | ``` 131 | 132 | ## Examples 133 | 134 | ### Live examples 135 | 136 | - [basic usage](https://jsfiddle.net/jeffbski/w3k5t83x/) - simple use or createMockStore to test actions that were dispatched (jsfiddle) 137 | - [async search](https://jsfiddle.net/jeffbski/a2cd2h96/) - async search using createMockStore to setup a test store (jsfiddle) 138 | 139 | ### Full examples 140 | 141 | - [browser-basic](./examples/browser-basic/src/App.test.js) - basic example of using createMockStore to test logic 142 | - [nodejs-basic](./examples/nodejs-basic/index.js) - simple Node.js example using createMockStore via Commonjs to test logic 143 | 144 | 145 | ## Get involved 146 | 147 | If you have input or ideas or would like to get involved, you may: 148 | 149 | - contact me via twitter @jeffbski - 150 | - open an issue on github to begin a discussion - 151 | - fork the repo and send a pull request (ideally with tests) - 152 | 153 | ## Supporters 154 | 155 | This project is supported by [CodeWinds Training](https://codewinds.com/) 156 | 157 | 158 | 159 | 160 | ## License - MIT 161 | 162 | - [MIT license](http://github.com/jeffbski/redux-logic-test/raw/master/LICENSE.md) 163 | -------------------------------------------------------------------------------- /examples/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "mocha": true 4 | }, 5 | "rules": { 6 | "import/no-extraneous-dependencies": 0 7 | } 8 | } -------------------------------------------------------------------------------- /examples/browser-basic/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env 15 | npm-debug.log* 16 | yarn-debug.log* 17 | yarn-error.log* 18 | 19 | -------------------------------------------------------------------------------- /examples/browser-basic/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). 2 | 3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). 5 | 6 | ## Table of Contents 7 | 8 | - [Updating to New Releases](#updating-to-new-releases) 9 | - [Sending Feedback](#sending-feedback) 10 | - [Folder Structure](#folder-structure) 11 | - [Available Scripts](#available-scripts) 12 | - [npm start](#npm-start) 13 | - [npm test](#npm-test) 14 | - [npm run build](#npm-run-build) 15 | - [npm run eject](#npm-run-eject) 16 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 17 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 18 | - [Changing the Page ``](#changing-the-page-title) 19 | - [Installing a Dependency](#installing-a-dependency) 20 | - [Importing a Component](#importing-a-component) 21 | - [Adding a Stylesheet](#adding-a-stylesheet) 22 | - [Post-Processing CSS](#post-processing-css) 23 | - [Adding Images and Fonts](#adding-images-and-fonts) 24 | - [Using the `public` Folder](#using-the-public-folder) 25 | - [Changing the HTML](#changing-the-html) 26 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 27 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 28 | - [Using Global Variables](#using-global-variables) 29 | - [Adding Bootstrap](#adding-bootstrap) 30 | - [Adding Flow](#adding-flow) 31 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 32 | - [Can I Use Decorators?](#can-i-use-decorators) 33 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 34 | - [Node](#node) 35 | - [Ruby on Rails](#ruby-on-rails) 36 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 37 | - [Using HTTPS in Development](#using-https-in-development) 38 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 39 | - [Running Tests](#running-tests) 40 | - [Filename Conventions](#filename-conventions) 41 | - [Command Line Interface](#command-line-interface) 42 | - [Version Control Integration](#version-control-integration) 43 | - [Writing Tests](#writing-tests) 44 | - [Testing Components](#testing-components) 45 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 46 | - [Initializing Test Environment](#initializing-test-environment) 47 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 48 | - [Coverage Reporting](#coverage-reporting) 49 | - [Continuous Integration](#continuous-integration) 50 | - [Disabling jsdom](#disabling-jsdom) 51 | - [Snapshot Testing](#snapshot-testing) 52 | - [Editor Integration](#editor-integration) 53 | - [Developing Components in Isolation](#developing-components-in-isolation) 54 | - [Making a Progressive Web App](#making-a-progressive-web-app) 55 | - [Deployment](#deployment) 56 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 57 | - [Building for Relative Paths](#building-for-relative-paths) 58 | - [Firebase](#firebase) 59 | - [GitHub Pages](#github-pages) 60 | - [Heroku](#heroku) 61 | - [Modulus](#modulus) 62 | - [Netlify](#netlify) 63 | - [Now](#now) 64 | - [S3 and CloudFront](#s3-and-cloudfront) 65 | - [Surge](#surge) 66 | - [Advanced Configuration](#advanced-configuration) 67 | - [Troubleshooting](#troubleshooting) 68 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 69 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 70 | - [`npm run build` silently fails](#npm-run-build-silently-fails) 71 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 72 | - [Something Missing?](#something-missing) 73 | 74 | ## Updating to New Releases 75 | 76 | Create React App is divided into two packages: 77 | 78 | * `create-react-app` is a global command-line utility that you use to create new projects. 79 | * `react-scripts` is a development dependency in the generated projects (including this one). 80 | 81 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 82 | 83 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. 84 | 85 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. 86 | 87 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. 88 | 89 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 90 | 91 | ## Sending Feedback 92 | 93 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 94 | 95 | ## Folder Structure 96 | 97 | After creation, your project should look like this: 98 | 99 | ``` 100 | my-app/ 101 | README.md 102 | node_modules/ 103 | package.json 104 | public/ 105 | index.html 106 | favicon.ico 107 | src/ 108 | App.css 109 | App.js 110 | App.test.js 111 | index.css 112 | index.js 113 | logo.svg 114 | ``` 115 | 116 | For the project to build, **these files must exist with exact filenames**: 117 | 118 | * `public/index.html` is the page template; 119 | * `src/index.js` is the JavaScript entry point. 120 | 121 | You can delete or rename the other files. 122 | 123 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 124 | You need to **put any JS and CSS files inside `src`**, or Webpack won’t see them. 125 | 126 | Only files inside `public` can be used from `public/index.html`.<br> 127 | Read instructions below for using assets from JavaScript and HTML. 128 | 129 | You can, however, create more top-level directories.<br> 130 | They will not be included in the production build so you can use them for things like documentation. 131 | 132 | ## Available Scripts 133 | 134 | In the project directory, you can run: 135 | 136 | ### `npm start` 137 | 138 | Runs the app in the development mode.<br> 139 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 140 | 141 | The page will reload if you make edits.<br> 142 | You will also see any lint errors in the console. 143 | 144 | ### `npm test` 145 | 146 | Launches the test runner in the interactive watch mode.<br> 147 | See the section about [running tests](#running-tests) for more information. 148 | 149 | ### `npm run build` 150 | 151 | Builds the app for production to the `build` folder.<br> 152 | It correctly bundles React in production mode and optimizes the build for the best performance. 153 | 154 | The build is minified and the filenames include the hashes.<br> 155 | Your app is ready to be deployed! 156 | 157 | See the section about [deployment](#deployment) for more information. 158 | 159 | ### `npm run eject` 160 | 161 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 162 | 163 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 164 | 165 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 166 | 167 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 168 | 169 | ## Syntax Highlighting in the Editor 170 | 171 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. 172 | 173 | ## Displaying Lint Output in the Editor 174 | 175 | >Note: this feature is available with `react-scripts@0.2.0` and higher. 176 | 177 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 178 | 179 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. 180 | 181 | You would need to install an ESLint plugin for your editor first. 182 | 183 | >**A note for Atom `linter-eslint` users** 184 | 185 | >If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked: 186 | 187 | ><img src="http://i.imgur.com/yVNNHJM.png" width="300"> 188 | 189 | 190 | >**For Visual Studio Code users** 191 | 192 | >VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line: 193 | 194 | >```js 195 | { 196 | // ... 197 | "extends": "react-app" 198 | } 199 | ``` 200 | 201 | Then add this block to the `package.json` file of your project: 202 | 203 | ```js 204 | { 205 | // ... 206 | "eslintConfig": { 207 | "extends": "react-app" 208 | } 209 | } 210 | ``` 211 | 212 | Finally, you will need to install some packages *globally*: 213 | 214 | ```sh 215 | npm install -g eslint-config-react-app@0.3.0 eslint@3.8.1 babel-eslint@7.0.0 eslint-plugin-react@6.4.1 eslint-plugin-import@2.0.1 eslint-plugin-jsx-a11y@2.2.3 eslint-plugin-flowtype@2.21.0 216 | ``` 217 | 218 | We recognize that this is suboptimal, but it is currently required due to the way we hide the ESLint dependency. The ESLint team is already [working on a solution to this](https://github.com/eslint/eslint/issues/3458) so this may become unnecessary in a couple of months. 219 | 220 | ## Changing the Page `<title>` 221 | 222 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 223 | 224 | Note that normally you wouldn't edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. 225 | 226 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. 227 | 228 | Finally, if you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). 229 | 230 | ## Installing a Dependency 231 | 232 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: 233 | 234 | ``` 235 | npm install --save <library-name> 236 | ``` 237 | 238 | ## Importing a Component 239 | 240 | This project setup supports ES6 modules thanks to Babel.<br> 241 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. 242 | 243 | For example: 244 | 245 | ### `Button.js` 246 | 247 | ```js 248 | import React, { Component } from 'react'; 249 | 250 | class Button extends Component { 251 | render() { 252 | // ... 253 | } 254 | } 255 | 256 | export default Button; // Don’t forget to use export default! 257 | ``` 258 | 259 | ### `DangerButton.js` 260 | 261 | 262 | ```js 263 | import React, { Component } from 'react'; 264 | import Button from './Button'; // Import a component from another file 265 | 266 | class DangerButton extends Component { 267 | render() { 268 | return <Button color="red" />; 269 | } 270 | } 271 | 272 | export default DangerButton; 273 | ``` 274 | 275 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. 276 | 277 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. 278 | 279 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. 280 | 281 | Learn more about ES6 modules: 282 | 283 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) 284 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 285 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 286 | 287 | ## Adding a Stylesheet 288 | 289 | This project setup uses [Webpack](https://webpack.github.io/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: 290 | 291 | ### `Button.css` 292 | 293 | ```css 294 | .Button { 295 | padding: 20px; 296 | } 297 | ``` 298 | 299 | ### `Button.js` 300 | 301 | ```js 302 | import React, { Component } from 'react'; 303 | import './Button.css'; // Tell Webpack that Button.js uses these styles 304 | 305 | class Button extends Component { 306 | render() { 307 | // You can use them as regular CSS styles 308 | return <div className="Button" />; 309 | } 310 | } 311 | ``` 312 | 313 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. 314 | 315 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. 316 | 317 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. 318 | 319 | ## Post-Processing CSS 320 | 321 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. 322 | 323 | For example, this: 324 | 325 | ```css 326 | .App { 327 | display: flex; 328 | flex-direction: row; 329 | align-items: center; 330 | } 331 | ``` 332 | 333 | becomes this: 334 | 335 | ```css 336 | .App { 337 | display: -webkit-box; 338 | display: -ms-flexbox; 339 | display: flex; 340 | -webkit-box-orient: horizontal; 341 | -webkit-box-direction: normal; 342 | -ms-flex-direction: row; 343 | flex-direction: row; 344 | -webkit-box-align: center; 345 | -ms-flex-align: center; 346 | align-items: center; 347 | } 348 | ``` 349 | 350 | There is currently no support for preprocessors such as Less, or for sharing variables across CSS files. 351 | 352 | ## Adding Images and Fonts 353 | 354 | With Webpack, using static assets like images and fonts works similarly to CSS. 355 | 356 | You can **`import` an image right in a JavaScript module**. This tells Webpack to include that image in the bundle. Unlike CSS imports, importing an image or a font gives you a string value. This value is the final image path you can reference in your code. 357 | 358 | Here is an example: 359 | 360 | ```js 361 | import React from 'react'; 362 | import logo from './logo.png'; // Tell Webpack this JS file uses this image 363 | 364 | console.log(logo); // /logo.84287d09.png 365 | 366 | function Header() { 367 | // Import result is the URL of your image 368 | return <img src={logo} alt="Logo" />; 369 | } 370 | 371 | export default Header; 372 | ``` 373 | 374 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 375 | 376 | This works in CSS too: 377 | 378 | ```css 379 | .Logo { 380 | background-image: url(./logo.png); 381 | } 382 | ``` 383 | 384 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. 385 | 386 | Please be advised that this is also a custom feature of Webpack. 387 | 388 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 389 | An alternative way of handling static assets is described in the next section. 390 | 391 | ## Using the `public` Folder 392 | 393 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 394 | 395 | ### Changing the HTML 396 | 397 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 398 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 399 | 400 | ### Adding Assets Outside of the Module System 401 | 402 | You can also add other assets to the `public` folder. 403 | 404 | Note that we normally encourage you to `import` assets in JavaScript files instead. 405 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-and-fonts). 406 | This mechanism provides a number of benefits: 407 | 408 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 409 | * Missing files cause compilation errors instead of 404 errors for your users. 410 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 411 | 412 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 413 | 414 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 415 | 416 | Inside `index.html`, you can use it like this: 417 | 418 | ```html 419 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 420 | ``` 421 | 422 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 423 | 424 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 425 | 426 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 427 | 428 | ```js 429 | render() { 430 | // Note: this is an escape hatch and should be used sparingly! 431 | // Normally we recommend using `import` for getting asset URLs 432 | // as described in “Adding Images and Fonts” above this section. 433 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 434 | } 435 | ``` 436 | 437 | Keep in mind the downsides of this approach: 438 | 439 | * None of the files in `public` folder get post-processed or minified. 440 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 441 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 442 | 443 | ### When to Use the `public` Folder 444 | 445 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-and-fonts) from JavaScript. 446 | The `public` folder is useful as a workaround for a number of less common cases: 447 | 448 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 449 | * You have thousands of images and need to dynamically reference their paths. 450 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 451 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 452 | 453 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 454 | 455 | ## Using Global Variables 456 | 457 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 458 | 459 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 460 | 461 | ```js 462 | const $ = window.$; 463 | ``` 464 | 465 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 466 | 467 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 468 | 469 | ## Adding Bootstrap 470 | 471 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 472 | 473 | Install React Bootstrap and Bootstrap from NPM. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 474 | 475 | ``` 476 | npm install react-bootstrap --save 477 | npm install bootstrap@3 --save 478 | ``` 479 | 480 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the ```src/index.js``` file: 481 | 482 | ```js 483 | import 'bootstrap/dist/css/bootstrap.css'; 484 | import 'bootstrap/dist/css/bootstrap-theme.css'; 485 | ``` 486 | 487 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 488 | 489 | ```js 490 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 491 | ``` 492 | 493 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 494 | 495 | ## Adding Flow 496 | 497 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 498 | 499 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 500 | 501 | To add Flow to a Create React App project, follow these steps: 502 | 503 | 1. Run `npm install --save-dev flow-bin`. 504 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 505 | 3. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 506 | 507 | Now you can run `npm run flow` to check the files for type errors. 508 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 509 | In the future we plan to integrate it into Create React App even more closely. 510 | 511 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 512 | 513 | ## Adding Custom Environment Variables 514 | 515 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 516 | 517 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 518 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 519 | `REACT_APP_`. 520 | 521 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). 522 | 523 | These environment variables will be defined for you on `process.env`. For example, having an environment 524 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`, in addition 525 | to `process.env.NODE_ENV`. 526 | 527 | >Note: Changing any environment variables will require you to restart the development server if it is running. 528 | 529 | These environment variables can be useful for displaying information conditionally based on where the project is 530 | deployed or consuming sensitive data that lives outside of version control. 531 | 532 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 533 | in the environment inside a `<form>`: 534 | 535 | ```jsx 536 | render() { 537 | return ( 538 | <div> 539 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 540 | <form> 541 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 542 | </form> 543 | </div> 544 | ); 545 | } 546 | ``` 547 | 548 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 549 | 550 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 551 | 552 | ```html 553 | <div> 554 | <small>You are running this application in <b>development</b> mode.</small> 555 | <form> 556 | <input type="hidden" value="abcdef" /> 557 | </form> 558 | </div> 559 | ``` 560 | 561 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 562 | 563 | ```js 564 | if (process.env.NODE_ENV !== 'production') { 565 | analytics.disable(); 566 | } 567 | ``` 568 | 569 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 570 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 571 | a `.env` file. 572 | 573 | ### Adding Temporary Environment Variables In Your Shell 574 | 575 | Defining environment variables can vary between OSes. It's also important to know that this manner is temporary for the 576 | life of the shell session. 577 | 578 | #### Windows (cmd.exe) 579 | 580 | ```cmd 581 | set REACT_APP_SECRET_CODE=abcdef&&npm start 582 | ``` 583 | 584 | (Note: the lack of whitespace is intentional.) 585 | 586 | #### Linux, macOS (Bash) 587 | 588 | ```bash 589 | REACT_APP_SECRET_CODE=abcdef npm start 590 | ``` 591 | 592 | ### Adding Development Environment Variables In `.env` 593 | 594 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 595 | 596 | To define permanent environment variables, create a file called `.env` in the root of your project: 597 | 598 | ``` 599 | REACT_APP_SECRET_CODE=abcdef 600 | ``` 601 | 602 | These variables will act as the defaults if the machine does not explicitly set them.<br> 603 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 604 | 605 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 606 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 607 | 608 | ## Can I Use Decorators? 609 | 610 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.<br> 611 | Create React App doesn’t support decorator syntax at the moment because: 612 | 613 | * It is an experimental proposal and is subject to change. 614 | * The current specification version is not officially supported by Babel. 615 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 616 | 617 | However in many cases you can rewrite decorator-based code without decorators just as fine.<br> 618 | Please refer to these two threads for reference: 619 | 620 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 621 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 622 | 623 | Create React App will add decorator support when the specification advances to a stable stage. 624 | 625 | ## Integrating with an API Backend 626 | 627 | These tutorials will help you to integrate your app with an API backend running on another port, 628 | using `fetch()` to access it. 629 | 630 | ### Node 631 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 632 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 633 | 634 | ### Ruby on Rails 635 | 636 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 637 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 638 | 639 | ## Proxying API Requests in Development 640 | 641 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 642 | 643 | People often serve the front-end React app from the same host and port as their backend implementation.<br> 644 | For example, a production setup might look like this after the app is deployed: 645 | 646 | ``` 647 | / - static server returns index.html with React app 648 | /todos - static server returns index.html with React app 649 | /api/todos - server handles any /api/* requests using the backend implementation 650 | ``` 651 | 652 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 653 | 654 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 655 | 656 | ```js 657 | "proxy": "http://localhost:4000", 658 | ``` 659 | 660 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. 661 | 662 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 663 | 664 | ``` 665 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 666 | ``` 667 | 668 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 669 | 670 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.<br> 671 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 672 | 673 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 674 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 675 | 676 | ## Using HTTPS in Development 677 | 678 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 679 | 680 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 681 | 682 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 683 | 684 | #### Windows (cmd.exe) 685 | 686 | ```cmd 687 | set HTTPS=true&&npm start 688 | ``` 689 | 690 | (Note: the lack of whitespace is intentional.) 691 | 692 | #### Linux, macOS (Bash) 693 | 694 | ```bash 695 | HTTPS=true npm start 696 | ``` 697 | 698 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 699 | 700 | ## Generating Dynamic `<meta>` Tags on the Server 701 | 702 | Since Create React App doesn’t support server rendering, you might be wondering how to make `<meta>` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 703 | 704 | ```html 705 | <!doctype html> 706 | <html lang="en"> 707 | <head> 708 | <meta property="og:title" content="%OG_TITLE%"> 709 | <meta property="og:description" content="%OG_DESCRIPTION%"> 710 | ``` 711 | 712 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `%OG_TITLE%`, `%OG_DESCRIPTION%`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 713 | 714 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 715 | 716 | ## Running Tests 717 | 718 | >Note: this feature is available with `react-scripts@0.3.0` and higher.<br> 719 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 720 | 721 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. 722 | 723 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. 724 | 725 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. 726 | 727 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. 728 | 729 | ### Filename Conventions 730 | 731 | Jest will look for test files with any of the following popular naming conventions: 732 | 733 | * Files with `.js` suffix in `__tests__` folders. 734 | * Files with `.test.js` suffix. 735 | * Files with `.spec.js` suffix. 736 | 737 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 738 | 739 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. 740 | 741 | ### Command Line Interface 742 | 743 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. 744 | 745 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: 746 | 747 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 748 | 749 | ### Version Control Integration 750 | 751 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests runs fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. 752 | 753 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. 754 | 755 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. 756 | 757 | ### Writing Tests 758 | 759 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. 760 | 761 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 762 | 763 | ```js 764 | import sum from './sum'; 765 | 766 | it('sums numbers', () => { 767 | expect(sum(1, 2)).toEqual(3); 768 | expect(sum(2, 2)).toEqual(4); 769 | }); 770 | ``` 771 | 772 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/api.html#expect-value).<br> 773 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/api.html#tobecalled) to create “spies” or mock functions. 774 | 775 | ### Testing Components 776 | 777 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. 778 | 779 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: 780 | 781 | ```js 782 | import React from 'react'; 783 | import ReactDOM from 'react-dom'; 784 | import App from './App'; 785 | 786 | it('renders without crashing', () => { 787 | const div = document.createElement('div'); 788 | ReactDOM.render(<App />, div); 789 | }); 790 | ``` 791 | 792 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. 793 | 794 | When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. 795 | 796 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). You can write a smoke test with it too: 797 | 798 | ```sh 799 | npm install --save-dev enzyme react-addons-test-utils 800 | ``` 801 | 802 | ```js 803 | import React from 'react'; 804 | import { shallow } from 'enzyme'; 805 | import App from './App'; 806 | 807 | it('renders without crashing', () => { 808 | shallow(<App />); 809 | }); 810 | ``` 811 | 812 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `<App>` and doesn’t go deeper. For example, even if `<App>` itself renders a `<Button>` that throws, this test will pass. Shallow rendering is great for isolated unit tests, but you may still want to create some full rendering tests to ensure the components integrate correctly. Enzyme supports [full rendering with `mount()`](http://airbnb.io/enzyme/docs/api/mount.html), and you can also use it for testing state changes and component lifecycle. 813 | 814 | You can read the [Enzyme documentation](http://airbnb.io/enzyme/) for more testing techniques. Enzyme documentation uses Chai and Sinon for assertions but you don’t have to use them because Jest provides built-in `expect()` and `jest.fn()` for spies. 815 | 816 | Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers: 817 | 818 | ```js 819 | import React from 'react'; 820 | import { shallow } from 'enzyme'; 821 | import App from './App'; 822 | 823 | it('renders welcome message', () => { 824 | const wrapper = shallow(<App />); 825 | const welcome = <h2>Welcome to React</h2>; 826 | // expect(wrapper.contains(welcome)).to.equal(true); 827 | expect(wrapper.contains(welcome)).toEqual(true); 828 | }); 829 | ``` 830 | 831 | All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/api.html#expect-value).<br> 832 | Nevertheless you can use a third-party assertion library like [Chai](http://chaijs.com/) if you want to, as described below. 833 | 834 | ### Using Third Party Assertion Libraries 835 | 836 | We recommend that you use `expect()` for assertions and `jest.fn()` for spies. If you are having issues with them please [file those against Jest](https://github.com/facebook/jest/issues/new), and we’ll fix them. We intend to keep making them better for React, supporting, for example, [pretty-printing React elements as JSX](https://github.com/facebook/jest/pull/1566). 837 | 838 | However, if you are used to other libraries, such as [Chai](http://chaijs.com/) and [Sinon](http://sinonjs.org/), or if you have existing code using them that you’d like to port over, you can import them normally like this: 839 | 840 | ```js 841 | import sinon from 'sinon'; 842 | import { expect } from 'chai'; 843 | ``` 844 | 845 | and then use them in your tests like you normally do. 846 | 847 | ### Initializing Test Environment 848 | 849 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 850 | 851 | If your app uses a browser API that you need to mock in your tests or if you just need a global setup before running your tests, add a `src/setupTests.js` to your project. It will be automatically executed before running your tests. 852 | 853 | For example: 854 | 855 | #### `src/setupTests.js` 856 | ```js 857 | const localStorageMock = { 858 | getItem: jest.fn(), 859 | setItem: jest.fn(), 860 | clear: jest.fn() 861 | }; 862 | global.localStorage = localStorageMock 863 | ``` 864 | 865 | ### Focusing and Excluding Tests 866 | 867 | You can replace `it()` with `xit()` to temporarily exclude a test from being executed.<br> 868 | Similarly, `fit()` lets you focus on a specific test without running any other tests. 869 | 870 | ### Coverage Reporting 871 | 872 | Jest has an integrated coverage reporter that works well with ES6 and requires no configuration.<br> 873 | Run `npm test -- --coverage` (note extra `--` in the middle) to include a coverage report like this: 874 | 875 | ![coverage report](http://i.imgur.com/5bFhnTS.png) 876 | 877 | Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow. 878 | 879 | ### Continuous Integration 880 | 881 | By default `npm test` runs the watcher with interactive CLI. However, you can force it to run tests once and finish the process by setting an environment variable called `CI`. 882 | 883 | When creating a build of your application with `npm run build` linter warnings are not checked by default. Like `npm test`, you can force the build to perform a linter warning check by setting the environment variable `CI`. If any warnings are encountered then the build fails. 884 | 885 | Popular CI servers already set the environment variable `CI` by default but you can do this yourself too: 886 | 887 | ### On CI servers 888 | #### Travis CI 889 | 890 | 1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page. 891 | 1. Add a `.travis.yml` file to your git repository. 892 | ``` 893 | language: node_js 894 | node_js: 895 | - 4 896 | - 6 897 | cache: 898 | directories: 899 | - node_modules 900 | script: 901 | - npm test 902 | - npm run build 903 | ``` 904 | 1. Trigger your first build with a git push. 905 | 1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed. 906 | 907 | ### On your own environment 908 | ##### Windows (cmd.exe) 909 | 910 | ```cmd 911 | set CI=true&&npm test 912 | ``` 913 | 914 | ```cmd 915 | set CI=true&&npm run build 916 | ``` 917 | 918 | (Note: the lack of whitespace is intentional.) 919 | 920 | ##### Linux, macOS (Bash) 921 | 922 | ```bash 923 | CI=true npm test 924 | ``` 925 | 926 | ```bash 927 | CI=true npm run build 928 | ``` 929 | 930 | The test command will force Jest to run tests once instead of launching the watcher. 931 | 932 | > If you find yourself doing this often in development, please [file an issue](https://github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows. 933 | 934 | The build command will check for linter warnings and fail if any are found. 935 | 936 | ### Disabling jsdom 937 | 938 | By default, the `package.json` of the generated project looks like this: 939 | 940 | ```js 941 | // ... 942 | "scripts": { 943 | // ... 944 | "test": "react-scripts test --env=jsdom" 945 | } 946 | ``` 947 | 948 | If you know that none of your tests depend on [jsdom](https://github.com/tmpvar/jsdom), you can safely remove `--env=jsdom`, and your tests will run faster.<br> 949 | To help you make up your mind, here is a list of APIs that **need jsdom**: 950 | 951 | * Any browser globals like `window` and `document` 952 | * [`ReactDOM.render()`](https://facebook.github.io/react/docs/top-level-api.html#reactdom.render) 953 | * [`TestUtils.renderIntoDocument()`](https://facebook.github.io/react/docs/test-utils.html#renderintodocument) ([a shortcut](https://github.com/facebook/react/blob/34761cf9a252964abfaab6faf74d473ad95d1f21/src/test/ReactTestUtils.js#L83-L91) for the above) 954 | * [`mount()`](http://airbnb.io/enzyme/docs/api/mount.html) in [Enzyme](http://airbnb.io/enzyme/index.html) 955 | 956 | In contrast, **jsdom is not needed** for the following APIs: 957 | 958 | * [`TestUtils.createRenderer()`](https://facebook.github.io/react/docs/test-utils.html#shallow-rendering) (shallow rendering) 959 | * [`shallow()`](http://airbnb.io/enzyme/docs/api/shallow.html) in [Enzyme](http://airbnb.io/enzyme/index.html) 960 | 961 | Finally, jsdom is also not needed for [snapshot testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html). 962 | 963 | ### Snapshot Testing 964 | 965 | Snapshot testing is a feature of Jest that automatically generates text snapshots of your components and saves them on the disk so if the UI output changes, you get notified without manually writing any assertions on the component output. [Read more about snapshot testing.](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html) 966 | 967 | ### Editor Integration 968 | 969 | If you use [Visual Studio Code](https://code.visualstudio.com), there is a [Jest extension](https://github.com/orta/vscode-jest) which works with Create React App out of the box. This provides a lot of IDE-like features while using a text editor: showing the status of a test run with potential fail messages inline, starting and stopping the watcher automatically, and offering one-click snapshot updates. 970 | 971 | ![VS Code Jest Preview](https://cloud.githubusercontent.com/assets/49038/20795349/a032308a-b7c8-11e6-9b34-7eeac781003f.png) 972 | 973 | ## Developing Components in Isolation 974 | 975 | Usually, in an app, you have a lot of UI components, and each of them has many different states. 976 | For an example, a simple button component could have following states: 977 | 978 | * With a text label. 979 | * With an emoji. 980 | * In the disabled mode. 981 | 982 | Usually, it’s hard to see these states without running a sample app or some examples. 983 | 984 | Create React App doesn't include any tools for this by default, but you can easily add [React Storybook](https://github.com/kadirahq/react-storybook) to your project. **It is a third-party tool that lets you develop components and see all their states in isolation from your app**. 985 | 986 | ![React Storybook Demo](http://i.imgur.com/7CIAWpB.gif) 987 | 988 | You can also deploy your Storybook as a static app. This way, everyone in your team can view and review different states of UI components without starting a backend server or creating an account in your app. 989 | 990 | **Here’s how to setup your app with Storybook:** 991 | 992 | First, install the following npm package globally: 993 | 994 | ```sh 995 | npm install -g getstorybook 996 | ``` 997 | 998 | Then, run the following command inside your app’s directory: 999 | 1000 | ```sh 1001 | getstorybook 1002 | ``` 1003 | 1004 | After that, follow the instructions on the screen. 1005 | 1006 | Learn more about React Storybook: 1007 | 1008 | * Screencast: [Getting Started with React Storybook](https://egghead.io/lessons/react-getting-started-with-react-storybook) 1009 | * [GitHub Repo](https://github.com/kadirahq/react-storybook) 1010 | * [Documentation](https://getstorybook.io/docs) 1011 | * [Snapshot Testing](https://github.com/kadirahq/storyshots) with React Storybook 1012 | 1013 | ## Making a Progressive Web App 1014 | 1015 | You can turn your React app into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps/) by following the steps in [this repository](https://github.com/jeffposnick/create-react-pwa). 1016 | 1017 | ## Deployment 1018 | 1019 | `npm run build` creates a `build` directory with a production build of your app. Set up your favourite HTTP server so that a visitor to your site is served `index.html`, and requests to static paths like `/static/js/main.<hash>.js` are served with the contents of the `/static/js/main.<hash>.js` file. For example, Python contains a built-in HTTP server that can serve static files: 1020 | 1021 | ```sh 1022 | cd build 1023 | python -m SimpleHTTPServer 9000 1024 | ``` 1025 | 1026 | If you're using [Node](https://nodejs.org/) and [Express](http://expressjs.com/) as a server, it might look like this: 1027 | 1028 | ```javascript 1029 | const express = require('express'); 1030 | const path = require('path'); 1031 | const app = express(); 1032 | 1033 | app.use(express.static('./build')); 1034 | 1035 | app.get('/', function (req, res) { 1036 | res.sendFile(path.join(__dirname, './build', 'index.html')); 1037 | }); 1038 | 1039 | app.listen(9000); 1040 | ``` 1041 | 1042 | Create React App is not opinionated about your choice of web server. Any static file server will do. The `build` folder with static assets is the only output produced by Create React App. 1043 | 1044 | However this is not quite enough if you use client-side routing. Read the next section if you want to support URLs like `/todos/42` in your single-page app. 1045 | 1046 | ### Serving Apps with Client-Side Routing 1047 | 1048 | If you use routers that use the HTML5 [`pushState` history API](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries) under the hood (for example, [React Router](https://github.com/ReactTraining/react-router) with `browserHistory`), many static file servers will fail. For example, if you used React Router with a route for `/todos/42`, the development server will respond to `localhost:3000/todos/42` properly, but an Express serving a production build as above will not. 1049 | 1050 | This is because when there is a fresh page load for a `/todos/42`, the server looks for the file `build/todos/42` and does not find it. The server needs to be configured to respond to a request to `/todos/42` by serving `index.html`. For example, we can amend our Express example above to serve `index.html` for any unknown paths: 1051 | 1052 | ```diff 1053 | app.use(express.static('./build')); 1054 | 1055 | -app.get('/', function (req, res) { 1056 | +app.get('/*', function (req, res) { 1057 | res.sendFile(path.join(__dirname, './build', 'index.html')); 1058 | }); 1059 | ``` 1060 | 1061 | Now requests to `/todos/42` will be handled correctly both in development and in production. 1062 | 1063 | ### Building for Relative Paths 1064 | 1065 | By default, Create React App produces a build assuming your app is hosted at the server root.<br> 1066 | To override this, specify the `homepage` in your `package.json`, for example: 1067 | 1068 | ```js 1069 | "homepage": "http://mywebsite.com/relativepath", 1070 | ``` 1071 | 1072 | This will let Create React App correctly infer the root path to use in the generated HTML file. 1073 | 1074 | #### Serving the Same Build from Different Paths 1075 | 1076 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 1077 | 1078 | If you are not using the HTML5 `pushState` history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your `package.json`: 1079 | 1080 | ```js 1081 | "homepage": ".", 1082 | ``` 1083 | 1084 | This will make sure that all the asset paths are relative to `index.html`. You will then be able to move your app from `http://mywebsite.com` to `http://mywebsite.com/relativepath` or even `http://mywebsite.com/relative/path` without having to rebuild it. 1085 | 1086 | ### Firebase 1087 | 1088 | Install the Firebase CLI if you haven't already by running `npm install -g firebase-tools`. Sign up for a [Firebase account](https://console.firebase.google.com/) and create a new project. Run `firebase login` and login with your previous created Firebase account. 1089 | 1090 | Then run the `firebase init` command from your project's root. You need to choose the **Hosting: Configure and deploy Firebase Hosting sites** and choose the Firebase project you created in the previous step. You will need to agree with `database.rules.json` being created, choose `build` as the public directory, and also agree to **Configure as a single-page app** by replying with `y`. 1091 | 1092 | ```sh 1093 | === Project Setup 1094 | 1095 | First, let's associate this project directory with a Firebase project. 1096 | You can create multiple project aliases by running firebase use --add, 1097 | but for now we'll just set up a default project. 1098 | 1099 | ? What Firebase project do you want to associate as default? Example app (example-app-fd690) 1100 | 1101 | === Database Setup 1102 | 1103 | Firebase Realtime Database Rules allow you to define how your data should be 1104 | structured and when your data can be read from and written to. 1105 | 1106 | ? What file should be used for Database Rules? database.rules.json 1107 | ✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json. 1108 | Future modifications to database.rules.json will update Database Rules when you run 1109 | firebase deploy. 1110 | 1111 | === Hosting Setup 1112 | 1113 | Your public directory is the folder (relative to your project directory) that 1114 | will contain Hosting assets to uploaded with firebase deploy. If you 1115 | have a build process for your assets, use your build's output directory. 1116 | 1117 | ? What do you want to use as your public directory? build 1118 | ? Configure as a single-page app (rewrite all urls to /index.html)? Yes 1119 | ✔ Wrote build/index.html 1120 | 1121 | i Writing configuration info to firebase.json... 1122 | i Writing project information to .firebaserc... 1123 | 1124 | ✔ Firebase initialization complete! 1125 | ``` 1126 | 1127 | Now, after you create a production build with `npm run build`, you can deploy it by running `firebase deploy`. 1128 | 1129 | ```sh 1130 | === Deploying to 'example-app-fd690'... 1131 | 1132 | i deploying database, hosting 1133 | ✔ database: rules ready to deploy. 1134 | i hosting: preparing build directory for upload... 1135 | Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully 1136 | ✔ hosting: 8 files uploaded successfully 1137 | i starting release process (may take several minutes)... 1138 | 1139 | ✔ Deploy complete! 1140 | 1141 | Project Console: https://console.firebase.google.com/project/example-app-fd690/overview 1142 | Hosting URL: https://example-app-fd690.firebaseapp.com 1143 | ``` 1144 | 1145 | For more information see [Add Firebase to your JavaScript Project](https://firebase.google.com/docs/web/setup). 1146 | 1147 | ### GitHub Pages 1148 | 1149 | >Note: this feature is available with `react-scripts@0.2.0` and higher. 1150 | 1151 | #### Step 1: Add `homepage` to `package.json` 1152 | 1153 | **The step below is important!**<br> 1154 | **If you skip it, your app will not deploy correctly.** 1155 | 1156 | Open your `package.json` and add a `homepage` field: 1157 | 1158 | ```js 1159 | "homepage": "https://myusername.github.io/my-app", 1160 | ``` 1161 | 1162 | Create React App uses the `homepage` field to determine the root URL in the built HTML file. 1163 | 1164 | #### Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json` 1165 | 1166 | Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages. 1167 | 1168 | To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run: 1169 | 1170 | ```sh 1171 | npm install --save-dev gh-pages 1172 | ``` 1173 | 1174 | Add the following scripts in your `package.json`: 1175 | 1176 | ```js 1177 | // ... 1178 | "scripts": { 1179 | // ... 1180 | "predeploy": "npm run build", 1181 | "deploy": "gh-pages -d build" 1182 | } 1183 | ``` 1184 | 1185 | The `predeploy` script will run automatically before `deploy` is run. 1186 | 1187 | #### Step 3: Deploy the site by running `npm run deploy` 1188 | 1189 | Then run: 1190 | 1191 | ```sh 1192 | npm run deploy 1193 | ``` 1194 | 1195 | #### Step 4: Ensure your project's settings use `gh-pages` 1196 | 1197 | Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch: 1198 | 1199 | <img src="http://i.imgur.com/HUjEr9l.png" width="500" alt="gh-pages branch setting"> 1200 | 1201 | #### Step 5: Optionally, configure the domain 1202 | 1203 | You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder. 1204 | 1205 | #### Notes on client-side routing 1206 | 1207 | GitHub Pages doesn't support routers that use the HTML5 `pushState` history API under the hood (for example, React Router using `browserHistory`). This is because when there is a fresh page load for a url like `http://user.github.io/todomvc/todos/42`, where `/todos/42` is a frontend route, the GitHub Pages server returns 404 because it knows nothing of `/todos/42`. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions: 1208 | 1209 | * You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to `hashHistory` for this effect, but the URL will be longer and more verbose (for example, `http://user.github.io/todomvc/#/todos/42?_k=yknaj`). [Read more](https://github.com/reactjs/react-router/blob/master/docs/guides/Histories.md#histories) about different history implementations in React Router. 1210 | * Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your `index.html` page with a special redirect parameter. You would need to add a `404.html` file with the redirection code to the `build` folder before deploying your project, and you’ll need to add code handling the redirect parameter to `index.html`. You can find a detailed explanation of this technique [in this guide](https://github.com/rafrex/spa-github-pages). 1211 | 1212 | ### Heroku 1213 | 1214 | Use the [Heroku Buildpack for Create React App](https://github.com/mars/create-react-app-buildpack).<br> 1215 | You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration). 1216 | 1217 | #### Resolving "Module not found: Error: Cannot resolve 'file' or 'directory'" 1218 | 1219 | Sometimes `npm run build` works locally but fails during deploy via Heroku with an error like this: 1220 | 1221 | ``` 1222 | remote: Failed to create a production build. Reason: 1223 | remote: Module not found: Error: Cannot resolve 'file' or 'directory' 1224 | MyDirectory in /tmp/build_1234/src 1225 | ``` 1226 | 1227 | This means you need to ensure that the lettercase of the file or directory you `import` matches the one you see on your filesystem or on GitHub. 1228 | 1229 | This is important because Linux (the operating system used by Heroku) is case sensitive. So `MyDirectory` and `mydirectory` are two distinct directories and thus, even though the project builds locally, the difference in case breaks the `import` statements on Heroku remotes. 1230 | 1231 | ### Modulus 1232 | 1233 | See the [Modulus blog post](http://blog.modulus.io/deploying-react-apps-on-modulus) on how to deploy your react app to Modulus. 1234 | 1235 | ## Netlify 1236 | 1237 | **To do a manual deploy to Netlify's CDN:** 1238 | 1239 | ```sh 1240 | npm install netlify-cli 1241 | netlify deploy 1242 | ``` 1243 | 1244 | Choose `build` as the path to deploy. 1245 | 1246 | **To setup continuous delivery:** 1247 | 1248 | With this setup Netlify will build and deploy when you push to git or open a pull request: 1249 | 1250 | 1. [Start a new netlify project](https://app.netlify.com/signup) 1251 | 2. Pick your Git hosting service and select your repository 1252 | 3. Click `Build your site` 1253 | 1254 | **Support for client-side routing:** 1255 | 1256 | To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules: 1257 | 1258 | ``` 1259 | /* /index.html 200 1260 | ``` 1261 | 1262 | When you build the project, Create React App will place the `public` folder contents into the build output. 1263 | 1264 | ### Now 1265 | 1266 | See [this example](https://github.com/xkawi/create-react-app-now) for a zero-configuration single-command deployment with [now](https://zeit.co/now). 1267 | 1268 | ### S3 and CloudFront 1269 | 1270 | See this [blog post](https://medium.com/@omgwtfmarc/deploying-create-react-app-to-s3-or-cloudfront-48dae4ce0af) on how to deploy your React app to Amazon Web Services [S3](https://aws.amazon.com/s3) and [CloudFront](https://aws.amazon.com/cloudfront/). 1271 | 1272 | ### Surge 1273 | 1274 | Install the Surge CLI if you haven't already by running `npm install -g surge`. Run the `surge` command and log in you or create a new account. You just need to specify the *build* folder and your custom domain, and you are done. 1275 | 1276 | ```sh 1277 | email: email@domain.com 1278 | password: ******** 1279 | project path: /path/to/project/build 1280 | size: 7 files, 1.8 MB 1281 | domain: create-react-app.surge.sh 1282 | upload: [====================] 100%, eta: 0.0s 1283 | propagate on CDN: [====================] 100% 1284 | plan: Free 1285 | users: email@domain.com 1286 | IP Address: X.X.X.X 1287 | 1288 | Success! Project is published and running at create-react-app.surge.sh 1289 | ``` 1290 | 1291 | Note that in order to support routers that use HTML5 `pushState` API, you may want to rename the `index.html` in your build folder to `200.html` before deploying to Surge. This [ensures that every URL falls back to that file](https://surge.sh/help/adding-a-200-page-for-client-side-routing). 1292 | 1293 | ## Advanced Configuration 1294 | 1295 | You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env). 1296 | 1297 | Variable | Development | Production | Usage 1298 | :--- | :---: | :---: | :--- 1299 | BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely. 1300 | HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host. 1301 | PORT | :white_check_mark: | :x: | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port. 1302 | HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode. 1303 | PUBLIC_URL | :x: | :white_check_mark: | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application. 1304 | CI | :large_orange_diamond: | :white_check_mark: | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default. 1305 | 1306 | ## Troubleshooting 1307 | 1308 | ### `npm start` doesn’t detect changes 1309 | 1310 | When you save a file while `npm start` is running, the browser should refresh with the updated code.<br> 1311 | If this doesn’t happen, try one of the following workarounds: 1312 | 1313 | * If your project is in a Dropbox folder, try moving it out. 1314 | * If the watcher doesn’t see a file called `index.js` and you’re referencing it by the folder name, you [need to restart the watcher](https://github.com/facebookincubator/create-react-app/issues/1164) due to a Webpack bug. 1315 | * Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in [“Working with editors supporting safe write”](https://webpack.github.io/docs/webpack-dev-server.html#working-with-editors-ides-supporting-safe-write). 1316 | * If your project path contains parentheses, try moving the project to a path without them. This is caused by a [Webpack watcher bug](https://github.com/webpack/watchpack/issues/42). 1317 | * On Linux and macOS, you might need to [tweak system settings](https://webpack.github.io/docs/troubleshooting.html#not-enough-watchers) to allow more watchers. 1318 | 1319 | If none of these solutions help please leave a comment [in this thread](https://github.com/facebookincubator/create-react-app/issues/659). 1320 | 1321 | ### `npm test` hangs on macOS Sierra 1322 | 1323 | If you run `npm test` and the console gets stuck after printing `react-scripts test --env=jsdom` to the console there might be a problem with your [Watchman](https://facebook.github.io/watchman/) installation as described in [facebookincubator/create-react-app#713](https://github.com/facebookincubator/create-react-app/issues/713). 1324 | 1325 | We recommend deleting `node_modules` in your project and running `npm install` (or `yarn` if you use it) first. If it doesn't help, you can try one of the numerous workarounds mentioned in these issues: 1326 | 1327 | * [facebook/jest#1767](https://github.com/facebook/jest/issues/1767) 1328 | * [facebook/watchman#358](https://github.com/facebook/watchman/issues/358) 1329 | * [ember-cli/ember-cli#6259](https://github.com/ember-cli/ember-cli/issues/6259) 1330 | 1331 | It is reported that installing Watchman 4.7.0 or newer fixes the issue. If you use [Homebrew](http://brew.sh/), you can run these commands to update it: 1332 | 1333 | ``` 1334 | watchman shutdown-server 1335 | brew update 1336 | brew reinstall watchman 1337 | ``` 1338 | 1339 | You can find [other installation methods](https://facebook.github.io/watchman/docs/install.html#build-install) on the Watchman documentation page. 1340 | 1341 | If this still doesn't help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`. 1342 | 1343 | There are also reports that *uninstalling* Watchman fixes the issue. So if nothing else helps, remove it from your system and try again. 1344 | 1345 | ### `npm run build` silently fails 1346 | 1347 | It is reported that `npm run build` can fail on machines with no swap space, which is common in cloud environments. If [the symptoms are matching](https://github.com/facebookincubator/create-react-app/issues/1133#issuecomment-264612171), consider adding some swap space to the machine you’re building on, or build the project locally. 1348 | 1349 | ### `npm run build` fails on Heroku 1350 | 1351 | This may be a problem with case sensitive filenames. 1352 | Please refer to [this section](#resolving-module-not-found-error-cannot-resolve-file-or-directory). 1353 | 1354 | ## Something Missing? 1355 | 1356 | If you have ideas for more “How To” recipes that should be on this page, [let us know](https://github.com/facebookincubator/create-react-app/issues) or [contribute some!](https://github.com/facebookincubator/create-react-app/edit/master/packages/react-scripts/template/README.md) 1357 | -------------------------------------------------------------------------------- /examples/browser-basic/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "browser-basic", 3 | "version": "0.1.0", 4 | "private": true, 5 | "devDependencies": { 6 | "cross-env": "^2.0.1", 7 | "react-scripts": "0.9.0", 8 | "redux-logic-test": "^1.0.1" 9 | }, 10 | "dependencies": { 11 | "react": "^15.4.2", 12 | "react-dom": "^15.4.2", 13 | "react-redux": "^5.0.2", 14 | "redux": "^3.6.0", 15 | "redux-logic": "^0.11.6", 16 | "rxjs": "^5.1.1" 17 | }, 18 | "scripts": { 19 | "setupAndRun": "npm install && npm test", 20 | "start": "react-scripts start", 21 | "build": "react-scripts build", 22 | "test": "cross-env CI=single-run BABEL_ENV=test react-scripts test --env=jsdom", 23 | "test:watch": "react-scripts test --env=jsdom", 24 | "eject": "react-scripts eject" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /examples/browser-basic/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeffbski/redux-logic-test/d08d3e39f81bb6af8e9dbf3b37e20410143aba01/examples/browser-basic/public/favicon.ico -------------------------------------------------------------------------------- /examples/browser-basic/public/index.html: -------------------------------------------------------------------------------- 1 | <!doctype html> 2 | <html lang="en"> 3 | <head> 4 | <meta charset="utf-8"> 5 | <meta name="viewport" content="width=device-width, initial-scale=1"> 6 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 7 | <!-- 8 | Notice the use of %PUBLIC_URL% in the tag above. 9 | It will be replaced with the URL of the `public` folder during the build. 10 | Only files inside the `public` folder can be referenced from the HTML. 11 | 12 | Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will 13 | work correctly both with client-side routing and a non-root public URL. 14 | Learn how to configure a non-root public URL by running `npm run build`. 15 | --> 16 | <title>React App 17 | 18 | 19 |
20 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /examples/browser-basic/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 80px; 8 | } 9 | 10 | .App-header { 11 | background-color: #222; 12 | height: 150px; 13 | padding: 20px; 14 | color: white; 15 | } 16 | 17 | .App-intro { 18 | font-size: large; 19 | } 20 | 21 | @keyframes App-logo-spin { 22 | from { transform: rotate(0deg); } 23 | to { transform: rotate(360deg); } 24 | } 25 | -------------------------------------------------------------------------------- /examples/browser-basic/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import logo from './logo.svg'; 4 | import './App.css'; 5 | 6 | function DisplayAnswer({ answer }) { 7 | return ( 8 |
9 | Answer: { answer } 10 |
11 | ); 12 | } 13 | const CDisplayAnswer = connect( 14 | state => ({ 15 | answer: state.answer 16 | }) 17 | )(DisplayAnswer); 18 | 19 | class App extends Component { 20 | render() { 21 | return ( 22 |
23 |
24 | logo 25 |

Welcome to React

26 |
27 | 28 |
29 | ); 30 | } 31 | } 32 | 33 | export default App; 34 | -------------------------------------------------------------------------------- /examples/browser-basic/src/App.logic.js: -------------------------------------------------------------------------------- 1 | import { createLogic } from 'redux-logic'; 2 | 3 | export const fooLogic = createLogic({ 4 | type: 'FOO', 5 | process({ API, getState, action }, dispatch, done) { 6 | API.get() 7 | .then(results => { 8 | dispatch({ type: 'FOO_SUCCESS', payload: results }); 9 | done(); 10 | }); 11 | } 12 | }); 13 | 14 | export default [ 15 | fooLogic 16 | ]; 17 | -------------------------------------------------------------------------------- /examples/browser-basic/src/App.reducer.js: -------------------------------------------------------------------------------- 1 | const initialState = { 2 | answer: null 3 | }; 4 | 5 | export default function reducer(state=initialState, action={}) { 6 | if (action.type === 'FOO_SUCCESS') { 7 | return { 8 | ...state, 9 | answer: action.payload 10 | }; 11 | } 12 | return state; 13 | } 14 | -------------------------------------------------------------------------------- /examples/browser-basic/src/App.test.js: -------------------------------------------------------------------------------- 1 | import { createMockStore } from 'redux-logic-test'; 2 | import appLogic from './App.logic'; 3 | import appReducer from './App.reducer'; 4 | 5 | // these can be customized/mocked for use in testing 6 | const injectedDeps = { 7 | API: { //simulate an async fetch 8 | get() { return Promise.resolve(42); } 9 | } 10 | }; 11 | 12 | 13 | describe('appLogic test without reducer', () => { 14 | 15 | describe('appLogic test without reducer', () => { 16 | let store; 17 | beforeEach(() => { 18 | store = createMockStore({ 19 | logic: appLogic, 20 | injectedDeps 21 | }); 22 | }); 23 | 24 | it('should fetch answer and dispatch', done => { 25 | store.dispatch({ type: 'FOO' }); // start fetching 26 | store.whenComplete(() => { // all logic has completed 27 | expect(store.actions).toEqual([ 28 | { type: 'FOO' }, 29 | { type: 'FOO_SUCCESS', payload: 42 } 30 | ]); 31 | done(); 32 | }); 33 | }); 34 | }); 35 | 36 | describe('appLogic test with reducer', () => { 37 | let store; 38 | beforeEach(() => { 39 | store = createMockStore({ 40 | reducer: appReducer, 41 | logic: appLogic, 42 | injectedDeps 43 | }); 44 | }); 45 | 46 | it('should fetch answer and dispatch', done => { 47 | store.dispatch({ type: 'FOO' }); // start fetching 48 | store.whenComplete(() => { // all logic has completed 49 | expect(store.actions).toEqual([ 50 | { type: 'FOO' }, 51 | { type: 'FOO_SUCCESS', payload: 42 } 52 | ]); 53 | done(); 54 | }); 55 | }); 56 | }); 57 | 58 | }); 59 | -------------------------------------------------------------------------------- /examples/browser-basic/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: sans-serif; 5 | } 6 | -------------------------------------------------------------------------------- /examples/browser-basic/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import { Provider } from 'react-redux'; 4 | import App from './App'; 5 | import configureStore from './store'; 6 | import './index.css'; 7 | 8 | const store = configureStore(); 9 | 10 | store.dispatch({ type: 'FOO' }); // start fetch 11 | 12 | ReactDOM.render( 13 | 14 | 15 | , 16 | document.getElementById('root') 17 | ); 18 | -------------------------------------------------------------------------------- /examples/browser-basic/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /examples/browser-basic/src/store.js: -------------------------------------------------------------------------------- 1 | import { createStore, applyMiddleware } from 'redux'; 2 | import { createLogicMiddleware } from 'redux-logic'; 3 | import appLogic from './App.logic'; 4 | import appReducer from './App.reducer'; 5 | 6 | export default function configureStore() { 7 | const logic = [ 8 | ...appLogic 9 | ]; 10 | 11 | const injectedDeps = { 12 | API: { //simulate an async fetch 13 | get() { return Promise.resolve(42); } 14 | } 15 | }; 16 | 17 | const logicMiddleware = createLogicMiddleware(logic, injectedDeps); 18 | const enhancer = applyMiddleware(logicMiddleware); 19 | const store = createStore(appReducer, enhancer); 20 | store.logicMiddleware = logicMiddleware; 21 | return store; 22 | } 23 | -------------------------------------------------------------------------------- /examples/buildAll.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Adapted from redux 3 | * Runs an ordered set of commands within each of the build directories. 4 | */ 5 | 6 | import fs from 'fs'; 7 | import path from 'path'; 8 | import { spawnSync } from 'child_process'; 9 | 10 | var exampleDirs = fs.readdirSync(__dirname).filter(file => 11 | fs.statSync(path.join(__dirname, file)).isDirectory()); 12 | 13 | // Ordering is important here 14 | var cmdArgs = [ 15 | { cmd: 'npm', args: ['run', 'setupAndRun'] } 16 | ]; 17 | 18 | for (const dir of exampleDirs) { 19 | for (const cmdArg of cmdArgs) { 20 | // declare opts in this scope to avoid https://github.com/joyent/node/issues/9158 21 | const opts = { 22 | cwd: path.join(__dirname, dir), 23 | stdio: 'inherit' 24 | }; 25 | process.stdout.write(`${opts.cwd}: ${cmdArg.cmd} ${cmdArg.args.join(' ')}\n`); 26 | let result = {}; 27 | if (process.platform === 'win32') { 28 | result = spawnSync(`${cmdArg.cmd}.cmd`, cmdArg.args, opts); 29 | } else { 30 | result = spawnSync(cmdArg.cmd, cmdArg.args, opts); 31 | } 32 | if (result.status !== 0) { 33 | throw new Error('Building examples exited with non-zero'); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /examples/fullBuildAll.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Adapted from redux 3 | * Runs an ordered set of commands within each of the build directories. 4 | */ 5 | 6 | import fs from 'fs'; 7 | import path from 'path'; 8 | import { spawnSync } from 'child_process'; 9 | 10 | var exampleDirs = fs.readdirSync(__dirname).filter(file => 11 | fs.statSync(path.join(__dirname, file)).isDirectory()); 12 | 13 | // Ordering is important here 14 | var cmdArgs = [ 15 | { cmd: 'rimraf', args: ['node_modules'] }, 16 | { cmd: 'npm', args: ['run', 'setupAndRun'] } 17 | ]; 18 | 19 | for (const dir of exampleDirs) { 20 | for (const cmdArg of cmdArgs) { 21 | // declare opts in this scope to avoid https://github.com/joyent/node/issues/9158 22 | const opts = { 23 | cwd: path.join(__dirname, dir), 24 | stdio: 'inherit' 25 | }; 26 | process.stdout.write(`${opts.cwd}: ${cmdArg.cmd} ${cmdArg.args.join(' ')}\n`); 27 | let result = {}; 28 | if (process.platform === 'win32') { 29 | result = spawnSync(`${cmdArg.cmd}.cmd`, cmdArg.args, opts); 30 | } else { 31 | result = spawnSync(cmdArg.cmd, cmdArg.args, opts); 32 | } 33 | if (result.status !== 0) { 34 | throw new Error('Building examples exited with non-zero'); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /examples/nodejs-basic/index.js: -------------------------------------------------------------------------------- 1 | const expect = require('expect'); 2 | const createMockStore = require('redux-logic-test').default.createMockStore; 3 | const createLogic = require('redux-logic').default.createLogic; 4 | 5 | const fooLogic = createLogic({ 6 | type: 'FOO', 7 | process(deps, dispatch, done) { 8 | const API = deps.API; 9 | API.get() 10 | .then(results => { 11 | dispatch({ type: 'FOO_SUCCESS', payload: results }); 12 | done(); 13 | }); 14 | } 15 | }); 16 | 17 | const api = { 18 | get() { return Promise.resolve(42); } 19 | }; 20 | 21 | const logic = [fooLogic]; // array of logic to use/test 22 | const injectedDeps = { // include what is needed for logic 23 | API: api // could include mocked API for easy testing 24 | }; 25 | 26 | const initialState = {}; // optionally set 27 | const reducer = (state /* ,action */) => { return state; }; // optional 28 | 29 | const store = createMockStore({ 30 | initialState, 31 | reducer, 32 | logic, 33 | injectedDeps 34 | }); 35 | 36 | store.dispatch({ type: 'FOO' }); // kick off fetching 37 | store.dispatch({ type: 'BAR' }); // other dispatches 38 | store.whenComplete(() => { // runs this fn when all logic is complete 39 | console.log('actions', store.actions); 40 | expect(store.actions).toEqual([ 41 | { type: 'FOO' }, 42 | { type: 'BAR' }, 43 | { type: 'FOO_SUCCESS', payload: 42 } 44 | ]); 45 | }); 46 | -------------------------------------------------------------------------------- /examples/nodejs-basic/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-basic", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "setupAndRun": "npm install && npm start", 8 | "start": "node index.js", 9 | "test": "npm start" 10 | }, 11 | "keywords": [], 12 | "author": "", 13 | "license": "ISC", 14 | "dependencies": { 15 | "redux": "^3.6.0", 16 | "redux-logic": "^0.11.6", 17 | "rxjs": "^5.1.1" 18 | }, 19 | "devDependencies": { 20 | "expect": "^1.20.2", 21 | "redux-logic-test": "^1.0.1" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "redux-logic-test", 3 | "version": "2.0.0", 4 | "description": "redux-logic test utilities to facilitate the testing of logic. Create mock store", 5 | "main": "build-lib/index.js", 6 | "browser": { 7 | "main": "dist/redux-logic-test.js" 8 | }, 9 | "browserify": { 10 | "transform": [ 11 | "loose-envify" 12 | ] 13 | }, 14 | "module": "build-es/index.js", 15 | "jsnext:main": "build-es/index.js", 16 | "files": [ 17 | "dist", 18 | "build-lib", 19 | "build-es", 20 | "src" 21 | ], 22 | "scripts": { 23 | "clean": "rimraf build-lib dist build-es", 24 | "lint": "eslint src test", 25 | "test": "cross-env BABEL_ENV=commonjs mocha --compilers js:babel-register --recursive -r ./test/setup.js", 26 | "test:watch": "npm test -- --watch", 27 | "check:src": "npm run lint && npm run test", 28 | "build:commonjs": "cross-env BABEL_ENV=commonjs babel src --out-dir build-lib", 29 | "build:es": "cross-env BABEL_ENV=es babel src --out-dir build-es", 30 | "build:umd": "cross-env MODTYPE=umd BABEL_ENV=commonjs NODE_ENV=development webpack src/index.js dist/redux-logic-test.js", 31 | "build:umd:min": "cross-env MODTYPE=umd BABEL_ENV=commonjs NODE_ENV=production webpack src/index.js dist/redux-logic-test.min.js", 32 | "analyze:umd": "cross-env MODTYPE=umd BABEL_ENV=commonjs NODE_ENV=development webpack src/index.js dist/redux-logic-test.js --json | webpack-bundle-size-analyzer", 33 | "build:examples": "cross-env BABEL_ENV=commonjs babel-node examples/buildAll.js", 34 | "fullbuild:examples": "cross-env BABEL_ENV=commonjs babel-node examples/fullBuildAll.js", 35 | "build": "npm run build:commonjs && npm run build:es && npm run build:umd && npm run build:umd:min", 36 | "prepublish": "npm run clean && npm run check:src && npm run build && check-es3-syntax build-lib/ --kill" 37 | }, 38 | "repository": { 39 | "type": "git", 40 | "url": "https://github.com/jeffbski/redux-logic-test.git" 41 | }, 42 | "keywords": [ 43 | "redux-logic", 44 | "test", 45 | "testing", 46 | "utilities", 47 | "mock", 48 | "store" 49 | ], 50 | "authors": [ 51 | "Jeff Barczewski (https://github.com/jeffbski)" 52 | ], 53 | "license": "MIT", 54 | "bugs": { 55 | "url": "https://github.com/jeffbski/redux-logic-test/issues" 56 | }, 57 | "homepage": "https://github.com/jeffbski/redux-logic-test", 58 | "dependencies": { 59 | "is-observable": "^0.2.0", 60 | "is-promise": "^2.1.0", 61 | "loose-envify": "^1.2.0" 62 | }, 63 | "peerDependencies": { 64 | "redux": ">=3.5.2", 65 | "redux-logic": ">=0.11.8" 66 | }, 67 | "devDependencies": { 68 | "babel-cli": "^6.3.15", 69 | "babel-core": "^6.3.15", 70 | "babel-eslint": "^7.0.0", 71 | "babel-loader": "^6.2.0", 72 | "babel-plugin-check-es2015-constants": "^6.3.13", 73 | "babel-plugin-transform-es2015-arrow-functions": "^6.3.13", 74 | "babel-plugin-transform-es2015-block-scoped-functions": "^6.3.13", 75 | "babel-plugin-transform-es2015-block-scoping": "^6.3.13", 76 | "babel-plugin-transform-es2015-classes": "^6.3.13", 77 | "babel-plugin-transform-es2015-computed-properties": "^6.3.13", 78 | "babel-plugin-transform-es2015-destructuring": "^6.3.13", 79 | "babel-plugin-transform-es2015-for-of": "^6.3.13", 80 | "babel-plugin-transform-es2015-function-name": "^6.3.13", 81 | "babel-plugin-transform-es2015-literals": "^6.3.13", 82 | "babel-plugin-transform-es2015-modules-commonjs": "^6.3.13", 83 | "babel-plugin-transform-es2015-object-super": "^6.3.13", 84 | "babel-plugin-transform-es2015-parameters": "^6.3.13", 85 | "babel-plugin-transform-es2015-shorthand-properties": "^6.3.13", 86 | "babel-plugin-transform-es2015-spread": "^6.3.13", 87 | "babel-plugin-transform-es2015-sticky-regex": "^6.3.13", 88 | "babel-plugin-transform-es2015-template-literals": "^6.3.13", 89 | "babel-plugin-transform-es2015-unicode-regex": "^6.3.13", 90 | "babel-plugin-transform-es3-member-expression-literals": "^6.5.0", 91 | "babel-plugin-transform-es3-property-literals": "^6.5.0", 92 | "babel-plugin-transform-object-rest-spread": "^6.3.13", 93 | "babel-register": "^6.3.13", 94 | "check-es3-syntax-cli": "^0.1.2", 95 | "core-js": "^2.4.1", 96 | "cross-env": "^2.0.1", 97 | "eslint": "^3.2.0", 98 | "eslint-config-airbnb-base": "^10.0.1", 99 | "eslint-plugin-import": "^2.2.0", 100 | "expect": "^1.8.0", 101 | "mocha": "^3.1.0", 102 | "redux": ">=3.5.2", 103 | "redux-logic": ">=0.11.8", 104 | "rimraf": "^2.5.4", 105 | "rxjs": "^5.0.3", 106 | "webpack": "^1.9.6" 107 | }, 108 | "npmName": "redux-logic-test", 109 | "npmFileMap": [ 110 | { 111 | "basePath": "/dist/", 112 | "files": [ 113 | "*.js" 114 | ] 115 | } 116 | ] 117 | } 118 | -------------------------------------------------------------------------------- /src/createMockStore.js: -------------------------------------------------------------------------------- 1 | import { createStore, applyMiddleware } from 'redux'; 2 | import { createLogicMiddleware } from 'redux-logic'; 3 | 4 | /* 5 | // specify as much as necessary for your particular test 6 | const store = createMockStore({ 7 | initialState: optionalObject, 8 | reducer: optionalFn, // default: identity reducer 9 | logic: optionalLogic, // default: [] 10 | injectedDeps: optionalObject, // default {} 11 | middleware: optionalArr // other mw, exclude logicMiddleware 12 | }); 13 | store.dispatch(...) // use as necessary for your test 14 | // when all inflight logic has all completed calls fn + returns promise 15 | store.whenComplete(fn) - shorthand for store.logicMiddleware.whenComplete(fn) 16 | store.actions - the actions dispatched, use store.resetActions() to clear 17 | store.resetActions() - clear store.actions 18 | // access the logicMiddleware created for logic/injectedDeps props 19 | // use addLogic, mergeNewLogic, replaceLogic, whenComplete, monitor$ 20 | store.logicMiddleware 21 | */ 22 | 23 | 24 | const defaultMockStoreOptions = { 25 | initialState: undefined, 26 | reducer(state /* , action */) { return state; }, // identity reducer 27 | logic: [], // used for the logicMiddleware that is created 28 | injectedDeps: {}, // used for the logicMiddleware that is created 29 | middleware: [] // other mw, exclude logicMiddleware from this array 30 | }; 31 | 32 | const ALLOWED_OPTIONS = Object.keys(defaultMockStoreOptions); 33 | 34 | function checkOptions(obj) { 35 | Object.keys(obj).forEach(k => { // check keys 36 | if (ALLOWED_OPTIONS.indexOf(k) === -1) { // no match 37 | throw new Error(`invalid option: ${k}`); 38 | } 39 | }); 40 | if (obj.reducer && typeof obj.reducer !== 'function') { 41 | throw new Error('reducer should be a function'); 42 | } 43 | if (obj.middleware && !Array.isArray(obj.middleware)) { 44 | throw new Error('middleware should be an array'); 45 | } 46 | } 47 | 48 | export default function createMockStore(options = {}) { 49 | checkOptions(options); // throws if any problems 50 | const opts = { 51 | ...defaultMockStoreOptions, 52 | ...options 53 | }; 54 | const { initialState, reducer, logic, injectedDeps, middleware } = opts; 55 | 56 | // track the actions dispatched using a custom mw added last 57 | const actions = []; 58 | const trackActionsMW = (/* store */) => next => action => { 59 | actions.push(action); 60 | return next(action); 61 | }; 62 | 63 | const logicMiddleware = createLogicMiddleware(logic, injectedDeps); 64 | const enhancer = applyMiddleware( 65 | logicMiddleware, 66 | ...middleware, 67 | trackActionsMW 68 | ); 69 | const store = createStore(reducer, initialState, enhancer); 70 | Object.defineProperty(store, 'actions', { // create store.actions getter 71 | enumerable: true, 72 | get() { return actions; } 73 | }); 74 | store.resetActions = () => { actions.length = 0; }; // truncate 75 | store.logicMiddleware = logicMiddleware; 76 | store.whenComplete = (fn) => logicMiddleware.whenComplete(fn); 77 | return store; 78 | } 79 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import createMockStore from './createMockStore'; 2 | 3 | export { createMockStore }; 4 | 5 | export default { 6 | createMockStore 7 | }; 8 | -------------------------------------------------------------------------------- /test/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "mocha": true 4 | }, 5 | "rules": { 6 | "import/no-extraneous-dependencies": 0 7 | } 8 | } -------------------------------------------------------------------------------- /test/createMockStore.spec.js: -------------------------------------------------------------------------------- 1 | import expect from 'expect'; 2 | import { createLogic } from 'redux-logic'; 3 | import { createMockStore } from '../src/index'; // redux-logic-test 4 | 5 | describe('createMockStore', () => { 6 | 7 | describe('no params', () => { 8 | let store; // defined later 9 | beforeEach('create store', () => { 10 | store = createMockStore(); 11 | }); 12 | 13 | it('creates a store with the proper properties and methods', () => { 14 | expect(store).toExist(); 15 | expect(store.getState).toBeA(Function); 16 | expect(store.dispatch).toBeA(Function); 17 | expect(store.subscribe).toBeA(Function); 18 | expect(store.whenComplete).toBeA(Function); 19 | expect(store.actions).toBeAn(Array); 20 | expect(store.resetActions).toBeA(Function); 21 | expect(store.logicMiddleware).toBeAn(Object); 22 | }); 23 | 24 | it('tracks the actions dispatched', done => { 25 | store.dispatch({ type: 'FOO' }); 26 | store.dispatch({ type: 'BAR' }); 27 | store.whenComplete(() => { 28 | expect(store.actions).toEqual([ 29 | { type: 'FOO' }, 30 | { type: 'BAR' } 31 | ]); 32 | done(); 33 | }); 34 | }); 35 | }); 36 | 37 | describe('invalid options', () => { 38 | it('throws an error', () => { 39 | const fn = () => { 40 | createMockStore({ thisIsWrong: 42 }); 41 | }; 42 | expect(fn).toThrow('invalid option: thisIsWrong'); 43 | }); 44 | }); 45 | 46 | describe('reducer not a function', () => { 47 | it('throws an error', () => { 48 | const fn = () => { 49 | createMockStore({ reducer: 1 }); // invalid should be fn 50 | }; 51 | expect(fn).toThrow('reducer should be a function'); 52 | }); 53 | }); 54 | 55 | describe('middleware not an array', () => { 56 | it('throws an error', () => { 57 | const fn = () => { 58 | createMockStore({ middleware: {} }); // invalid should be an array 59 | }; 60 | expect(fn).toThrow('middleware should be an array'); 61 | }); 62 | }); 63 | 64 | describe('w/initialState', () => { 65 | let store; // defined later 66 | beforeEach('create store', () => { 67 | store = createMockStore({ initialState: { a: 1 } }); 68 | }); 69 | 70 | it('should have the correct state', () => { 71 | expect(store.getState()).toEqual({ a: 1 }); 72 | }); 73 | }); 74 | 75 | describe('w/reducer', () => { 76 | let store; // defined later 77 | beforeEach('create store', () => { 78 | const initialState = { 79 | count: 0 80 | }; 81 | const reducer = (state = initialState, action = {}) => { 82 | if (action.type === 'INCR') { 83 | return { count: state.count + 1 }; 84 | } 85 | return state; 86 | }; 87 | store = createMockStore({ reducer }); 88 | }); 89 | 90 | it('should adjust state', () => { 91 | expect(store.getState()).toEqual({ count: 0 }); 92 | store.dispatch({ type: 'INCR' }); 93 | store.dispatch({ type: 'INCR' }); 94 | expect(store.getState()).toEqual({ count: 2 }); 95 | }); 96 | }); 97 | 98 | describe('w/logic', () => { 99 | let store; // defined later 100 | beforeEach('create store', () => { 101 | const fooLogic = createLogic({ 102 | type: 'FOO', 103 | process() { 104 | return { type: 'FOO_SUCCESS' }; 105 | } 106 | }); 107 | const logic = [fooLogic]; 108 | store = createMockStore({ logic }); 109 | }); 110 | 111 | it('should adjust state', done => { 112 | store.dispatch({ type: 'FOO' }); 113 | store.whenComplete(() => { 114 | expect(store.actions).toEqual([ 115 | { type: 'FOO' }, 116 | { type: 'FOO_SUCCESS' } 117 | ]); 118 | done(); 119 | }); 120 | }); 121 | 122 | it('should clear the actions when resetAction is called', done => { 123 | store.dispatch({ type: 'FOO' }); 124 | store.whenComplete(() => { 125 | expect(store.actions).toEqual([ 126 | { type: 'FOO' }, 127 | { type: 'FOO_SUCCESS' } 128 | ]); 129 | store.resetActions(); 130 | expect(store.actions).toEqual([]); 131 | done(); 132 | }); 133 | }); 134 | 135 | it('should complete even if no dispatches', done => { 136 | store.whenComplete(() => { 137 | expect(store.actions).toEqual([]); 138 | done(); 139 | }); 140 | }); 141 | 142 | it('should complete even with non-matching dispatches', done => { 143 | store.dispatch({ type: 'BAR' }); 144 | store.dispatch({ type: 'BAZ' }); 145 | store.whenComplete(() => { 146 | expect(store.actions).toEqual([ 147 | { type: 'BAR' }, 148 | { type: 'BAZ' } 149 | ]); 150 | done(); 151 | }); 152 | }); 153 | 154 | }); 155 | 156 | describe('w/injectedDeps', () => { 157 | let store; // defined later 158 | beforeEach('create store', () => { 159 | const injectedDeps = { cat: 42 }; 160 | store = createMockStore({ injectedDeps }); 161 | }); 162 | 163 | it('should provide deps to logic', done => { 164 | const fooLogic = createLogic({ 165 | type: 'FOO', 166 | process({ cat }) { 167 | expect(cat).toBe(42); 168 | done(); 169 | } 170 | }); 171 | const logic = [fooLogic]; 172 | store.logicMiddleware.mergeNewLogic(logic); 173 | store.dispatch({ type: 'FOO' }); 174 | }); 175 | }); 176 | 177 | describe('w/middleware', () => { 178 | let store; // defined later 179 | beforeEach('create store', () => { 180 | const barMW = (/* store */) => next => action => { 181 | if (typeof action === 'function') { 182 | return next(action()); 183 | } 184 | return next(action); 185 | }; 186 | const middleware = [barMW]; 187 | store = createMockStore({ middleware }); 188 | }); 189 | 190 | it('actions should pass through mw', () => { 191 | store.dispatch(() => ({ type: 'DOG' })); 192 | expect(store.actions).toEqual([{ type: 'DOG' }]); 193 | }); 194 | }); 195 | 196 | describe('logic+injectedDeps', () => { 197 | let store; // defined later 198 | beforeEach('create store', () => { 199 | const fooLogic = createLogic({ 200 | type: 'FOO', 201 | process({ cat }) { 202 | expect(cat).toBe(42); 203 | return Promise.resolve({ type: 'FOO_SUCCESS' }); 204 | } 205 | }); 206 | const logic = [fooLogic]; 207 | const injectedDeps = { cat: 42 }; 208 | store = createMockStore({ logic, injectedDeps }); 209 | }); 210 | 211 | it('should dispatch', done => { 212 | store.dispatch({ type: 'FOO' }); 213 | store.dispatch({ type: 'BAR' }); 214 | store.whenComplete(() => { 215 | expect(store.actions).toEqual([ 216 | { type: 'FOO' }, 217 | { type: 'BAR' }, 218 | { type: 'FOO_SUCCESS' } 219 | ]); 220 | done(); 221 | }); 222 | }); 223 | }); 224 | 225 | describe('logic+middleware', () => { 226 | let store; // defined later 227 | beforeEach('create store', () => { 228 | const fooLogic = createLogic({ 229 | type: 'FOO', 230 | process() { 231 | return Promise.resolve({ type: 'FOO_SUCCESS' }); 232 | } 233 | }); 234 | const logic = [fooLogic]; 235 | const barMW = (/* store */) => next => action => { 236 | if (typeof action === 'function') { 237 | return next(action()); // execute action 238 | } 239 | return next(action); 240 | }; 241 | const middleware = [barMW]; 242 | store = createMockStore({ logic, middleware }); 243 | }); 244 | 245 | it('should dispatch', done => { 246 | store.dispatch({ type: 'FOO' }); 247 | store.dispatch(() => ({ type: 'BAR' })); // fn 248 | store.whenComplete(() => { 249 | expect(store.actions).toEqual([ 250 | { type: 'FOO' }, 251 | { type: 'BAR' }, 252 | { type: 'FOO_SUCCESS' } 253 | ]); 254 | done(); 255 | }); 256 | }); 257 | }); 258 | 259 | describe('kitchen sink', () => { 260 | let store; // defined later 261 | beforeEach('create store', () => { 262 | const reducer = (state, action) => { 263 | if (action.type === 'INCR') { 264 | return { ...state, count: state.count + 1 }; 265 | } 266 | return state; 267 | }; 268 | const fooLogic = createLogic({ 269 | type: 'FOO', 270 | process({ getState, cat }) { 271 | expect(cat).toBe(42); 272 | return Promise.resolve({ 273 | type: 'FOO_SUCCESS', 274 | count: getState().count 275 | }); 276 | } 277 | }); 278 | const logic = [fooLogic]; 279 | const injectedDeps = { cat: 42 }; 280 | const barMW = (/* store */) => next => action => { 281 | if (typeof action === 'function') { 282 | return next(action()); 283 | } 284 | return next(action); 285 | }; 286 | const middleware = [barMW]; 287 | store = createMockStore({ 288 | initialState: { count: 10 }, 289 | reducer, 290 | logic, 291 | injectedDeps, 292 | middleware 293 | }); 294 | }); 295 | 296 | it('should dispatch actions updating state', done => { 297 | expect(store.getState()).toEqual({ count: 10 }); 298 | store.dispatch({ type: 'INCR' }); 299 | store.dispatch({ type: 'INCR' }); 300 | expect(store.getState()).toEqual({ count: 12 }); 301 | expect(store.actions).toEqual([ 302 | { type: 'INCR' }, 303 | { type: 'INCR' } 304 | ]); 305 | store.resetActions(); 306 | expect(store.actions).toEqual([]); 307 | store.dispatch(() => ({ type: 'BAR' })); // fn, exec in mw 308 | expect(store.actions).toEqual([{ type: 'BAR' }]); 309 | store.resetActions(); 310 | store.dispatch({ type: 'FOO' }); 311 | store.whenComplete(() => { 312 | expect(store.actions).toEqual([ 313 | { type: 'FOO' }, 314 | { type: 'FOO_SUCCESS', count: 12 } 315 | ]); 316 | done(); 317 | }); 318 | }); 319 | }); 320 | 321 | }); 322 | -------------------------------------------------------------------------------- /test/setup.js: -------------------------------------------------------------------------------- 1 | import 'core-js/fn/promise'; // polyfill promise for tests 2 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var webpack = require('webpack'); 4 | 5 | var env = process.env.NODE_ENV; 6 | var modType = process.env.MODTYPE; // 'umd' or undefined 7 | var config = { 8 | module: { 9 | loaders: [ 10 | { test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ } 11 | ] 12 | }, 13 | output: { 14 | library: 'ReduxLogicTest', 15 | libraryTarget: 'umd' 16 | }, 17 | plugins: [ 18 | new webpack.optimize.OccurrenceOrderPlugin(), 19 | new webpack.DefinePlugin({ 20 | 'process.env.NODE_ENV': JSON.stringify(env) 21 | }) 22 | ] 23 | }; 24 | 25 | if (env === 'production') { 26 | config.plugins.push( 27 | new webpack.optimize.UglifyJsPlugin({ 28 | compressor: { 29 | pure_getters: true, 30 | unsafe: true, 31 | unsafe_comps: true, 32 | warnings: false 33 | } 34 | }) 35 | ); 36 | } 37 | 38 | if (modType === 'umd') { 39 | config.externals = { 40 | "redux": "Redux", 41 | "redux-logic": "ReduxLogic" 42 | }; 43 | } 44 | 45 | module.exports = config; 46 | --------------------------------------------------------------------------------