├── .gitignore ├── README.md ├── es6 └── classes.js ├── flashcardpro ├── .gitignore ├── README.md ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json ├── src │ ├── actions │ │ ├── index.js │ │ └── index.test.js │ ├── components │ │ ├── App.js │ │ ├── App.test.js │ │ ├── Card.js │ │ ├── Card.test.js │ │ ├── Stack.js │ │ ├── Stack.test.js │ │ ├── StackForm.js │ │ ├── StackForm.test.js │ │ ├── StackList.js │ │ └── StackList.test.js │ ├── data │ │ ├── fixtures.js │ │ └── stacks.json │ ├── index.css │ ├── index.js │ └── reducers │ │ ├── index.js │ │ └── index.test.js └── yarn.lock ├── flashcardpro_parcel ├── .gitignore ├── README.md ├── index.html ├── package.json ├── public │ ├── favicon.ico │ └── manifest.json ├── src │ ├── actions │ │ ├── index.js │ │ └── index.test.js │ ├── components │ │ ├── App.js │ │ ├── App.test.js │ │ ├── Card.js │ │ ├── Card.test.js │ │ ├── Stack.js │ │ ├── Stack.test.js │ │ ├── StackForm.js │ │ ├── StackForm.test.js │ │ ├── StackList.js │ │ └── StackList.test.js │ ├── data │ │ ├── fixtures.js │ │ └── stacks.json │ ├── index.css │ ├── index.js │ └── reducers │ │ ├── index.js │ │ └── index.test.js └── yarn.lock ├── jeopardy ├── .gitignore ├── README.md ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json ├── src │ ├── actions │ │ ├── index.js │ │ └── index.test.js │ ├── components │ │ ├── App.js │ │ ├── App.test.js │ │ ├── Category.js │ │ ├── Category.test.js │ │ ├── Clue.js │ │ └── Clue.test.js │ ├── data │ │ └── fixtures.js │ ├── index.css │ ├── index.js │ └── reducers │ │ ├── index.js │ │ └── index.test.js └── yarn.lock └── notetoself ├── .gitignore ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html └── manifest.json ├── src ├── components │ ├── App.js │ ├── App.test.js │ ├── Note.js │ └── Note.test.js ├── index.css └── index.js └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | *node_modules/* 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React, Redux, & Enzmye - Mastering Apps & Tests 2 | "React, Redux, & Enzmye - Mastering Apps & Tests": Official guide repo used to accompany video lessons. 3 | 4 | This provides the completed projects for: 5 | - notetoself + tests 6 | - flashcardpro + tests 7 | - jeopardy + tests 8 | 9 | Check out the original course: 10 | https://www.udemy.com/react-testing/ 11 | -------------------------------------------------------------------------------- /es6/classes.js: -------------------------------------------------------------------------------- 1 | class Animal { 2 | constructor(name, color) { 3 | this.name = name; 4 | this.color = color; 5 | } 6 | 7 | speak() { 8 | // console.log("Hi, I'm " + this.name + ", and I'm " + this.color); 9 | console.log(`Hi, I'm ${this.name}, and I'm ${this.color}`); 10 | } 11 | } 12 | 13 | class Lion extends Animal { 14 | constructor(name, color, role, home) { 15 | super(name, color); 16 | 17 | this.role = role; 18 | this.home = home; 19 | } 20 | 21 | roar() { 22 | console.log(`I'm the ${this.role} of ${this.home}`); 23 | } 24 | } 25 | 26 | let lion = new Lion("Mufasa", "golden", "king", "Pride rock"); 27 | let lion_2 = new Lion("Scar", "maroon", "outcast", "the shadowlands"); 28 | 29 | lion_2.speak(); 30 | lion_2.roar(); -------------------------------------------------------------------------------- /flashcardpro/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://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.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /flashcardpro/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "flashcardpro", 3 | "version": "0.1.0", 4 | "private": true, 5 | "devDependencies": { 6 | "enzyme": "^2.9.1", 7 | "react-scripts": "1.0.11", 8 | "react-test-renderer": "^15.6.1" 9 | }, 10 | "dependencies": { 11 | "react": "^15.6.1", 12 | "react-bootstrap": "^0.31.2", 13 | "react-dom": "^15.6.1", 14 | "react-redux": "^5.0.6", 15 | "react-router-dom": "^4.1.2", 16 | "redux": "^3.7.2" 17 | }, 18 | "scripts": { 19 | "start": "react-scripts start", 20 | "build": "react-scripts build", 21 | "test": "react-scripts test --env=jsdom", 22 | "eject": "react-scripts eject" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /flashcardpro/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/15Dkatz/react-testing/66f64b5d55e48b7f5930f137dd568a0d9305d27e/flashcardpro/public/favicon.ico -------------------------------------------------------------------------------- /flashcardpro/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 22 | 23 | 24 | React App 25 | 26 | 27 | 30 |
31 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /flashcardpro/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "192x192", 8 | "type": "image/png" 9 | } 10 | ], 11 | "start_url": "./index.html", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /flashcardpro/src/actions/index.js: -------------------------------------------------------------------------------- 1 | export const SET_STACK = 'SET_STACK'; 2 | export const LOAD_STACKS = 'LOAD_STACKS'; 3 | export const ADD_STACK = 'ADD_STACK'; 4 | 5 | export function setStack(stack) { 6 | return { 7 | type: SET_STACK, 8 | stack 9 | }; 10 | } 11 | 12 | export function loadStacks(stacks) { 13 | return { 14 | type: LOAD_STACKS, 15 | stacks 16 | } 17 | } 18 | 19 | export function addStack(stack) { 20 | return { 21 | type: ADD_STACK, 22 | stack 23 | } 24 | } -------------------------------------------------------------------------------- /flashcardpro/src/actions/index.test.js: -------------------------------------------------------------------------------- 1 | import * as actions from './index'; 2 | import { stack, stacks } from '../data/fixtures'; 3 | 4 | describe('actions', () => { 5 | it('creates an action to set the main stack', () => { 6 | const expectedAction = { type: actions.SET_STACK, stack }; 7 | 8 | expect(actions.setStack(stack)).toEqual(expectedAction); 9 | }); 10 | 11 | it('creates an action to add a stack', () => { 12 | const expectedAction = { type: actions.ADD_STACK, stack }; 13 | 14 | expect(actions.addStack(stack)).toEqual(expectedAction); 15 | }); 16 | 17 | it('creates an action to load stacks', () => { 18 | const expectedAction = { type: actions.LOAD_STACKS, stacks }; 19 | 20 | expect(actions.loadStacks(stacks)).toEqual(expectedAction); 21 | }); 22 | }); -------------------------------------------------------------------------------- /flashcardpro/src/components/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { Link } from 'react-router-dom'; 3 | import StackList from './StackList'; 4 | 5 | const App = () => { 6 | return ( 7 |
8 |

Flashcard Pro

9 |
10 | 11 |
12 |

Create a New Stack

13 |
14 | ) 15 | } 16 | 17 | export default App; -------------------------------------------------------------------------------- /flashcardpro/src/components/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import App from './App'; 4 | 5 | describe('App', () => { 6 | const app = shallow(); 7 | 8 | it('renders the `Flashcard Pro` title', () => { 9 | expect(app.find('h2').text()).toEqual('Flashcard Pro') 10 | }); 11 | 12 | it('renders the StackList', () => { 13 | expect(app.find('Connect(StackList)').exists()).toBe(true); 14 | }); 15 | 16 | it('renders a link to create new stacks', () => { 17 | expect(app.find('Link h4').text()).toEqual('Create a New Stack'); 18 | }); 19 | }); -------------------------------------------------------------------------------- /flashcardpro/src/components/Card.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | 3 | class Card extends Component { 4 | constructor() { 5 | super(); 6 | 7 | this.state = { reveal: false }; 8 | } 9 | 10 | render() { 11 | const { prompt, answer } = this.props.card; 12 | 13 | return ( 14 |
this.setState({ reveal: true })}> 15 |
16 |

{prompt}

17 |
18 |
19 |

20 | {answer} 21 |

22 |
23 |
24 | ) 25 | } 26 | } 27 | 28 | export default Card; -------------------------------------------------------------------------------- /flashcardpro/src/components/Card.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import Card from './Card'; 4 | 5 | const props = { 6 | card: { prompt: 'test prompt', answer: 'test answer'} 7 | }; 8 | 9 | describe('Card', () => { 10 | const card = shallow(); 11 | 12 | it('sets `reveal` to be `false`', () => { 13 | expect(card.state().reveal).toBe(false); 14 | }); 15 | 16 | it('renders the card prompt', () => { 17 | expect(card.find('.card-prompt h4').text()).toEqual(props.card.prompt); 18 | }); 19 | 20 | it('renders the card answer', () => { 21 | expect(card.find('.card-answer h4').text()).toEqual(props.card.answer); 22 | }); 23 | 24 | it('applies the `text-hidden` class to the card answer', () => { 25 | expect(card.find('.card-answer h4').hasClass('text-hidden')).toBe(true); 26 | }); 27 | 28 | describe('when clicking on the card', () => { 29 | beforeEach(() => card.simulate('click')); 30 | 31 | it('updates `reveal` to be `true`', () => { 32 | expect(card.state().reveal).toBe(true); 33 | }); 34 | 35 | it('applies the `text-revealed` class to the card answer', () => { 36 | expect(card.find('.card-answer h4').hasClass('text-revealed')).toBe(true); 37 | }); 38 | }); 39 | }); -------------------------------------------------------------------------------- /flashcardpro/src/components/Stack.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Link } from 'react-router-dom'; 4 | import Card from './Card'; 5 | 6 | export const Stack = ({ stack: { title, cards } }) => { 7 | return ( 8 |
9 | 10 |

Home

11 | 12 |

{title}

13 |
14 | { 15 | cards.map(card => { 16 | return ( 17 | 18 | ) 19 | }) 20 | } 21 |
22 | ) 23 | } 24 | 25 | function mapStateToProps(state) { 26 | return { stack: state.stack }; 27 | } 28 | 29 | export default connect(mapStateToProps, null)(Stack); -------------------------------------------------------------------------------- /flashcardpro/src/components/Stack.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import { Stack } from './Stack'; 4 | import { stack } from '../data/fixtures'; 5 | 6 | const props = { stack }; 7 | 8 | describe('Stack', () => { 9 | const stack = shallow(); 10 | 11 | it('renders the title', () => { 12 | expect(stack.find('h3').text()).toEqual(props.stack.title); 13 | }); 14 | 15 | it('renders the Link home', () => { 16 | expect(stack.find('Link h4').text()).toEqual('Home'); 17 | }); 18 | 19 | it('renders the correct number of cards', () => { 20 | expect(stack.find('Card').length).toEqual(props.stack.cards.length); 21 | }); 22 | }); -------------------------------------------------------------------------------- /flashcardpro/src/components/StackForm.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Link } from 'react-router-dom'; 4 | import { Form, FormGroup, FormControl, ControlLabel, Button } from 'react-bootstrap'; 5 | import { addStack } from '../actions'; 6 | 7 | export class StackForm extends Component { 8 | constructor() { 9 | super(); 10 | 11 | this.state = { 12 | title: '', 13 | cards: [] 14 | } 15 | } 16 | 17 | addCard() { 18 | const { cards } = this.state; 19 | 20 | cards.push({ id: cards.length, prompt: '', answer: '' }); 21 | 22 | this.setState({ cards }); 23 | } 24 | 25 | updateCardPart(event, index, part) { 26 | const { cards } = this.state; 27 | 28 | cards[index][part] = event.target.value; 29 | 30 | this.setState({ cards }); 31 | } 32 | 33 | addStack() { 34 | this.props.addStack(this.state); 35 | } 36 | 37 | render() { 38 | return ( 39 |
40 | 41 |

Home

42 | 43 |

Create a New Stack

44 |
45 |
46 | 47 | Title: 48 | {' '} 49 | this.setState({ title: event.target.value })} /> 50 | 51 | { 52 | this.state.cards.map((card, index) => { 53 | return ( 54 |
55 |
56 | 57 | Prompt: 58 | {' '} 59 | this.updateCardPart(event, index, 'prompt')} 61 | /> 62 | {' '} 63 | Answer: 64 | {' '} 65 | this.updateCardPart(event, index, 'answer')} 67 | /> 68 | 69 |
70 | ) 71 | }) 72 | } 73 |
74 |
75 | 76 | {' '} 77 | 78 |
79 | ) 80 | } 81 | } 82 | 83 | export default connect(null, { addStack })(StackForm); -------------------------------------------------------------------------------- /flashcardpro/src/components/StackForm.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import { StackForm } from './StackForm'; 4 | 5 | const changeTitle = 'change title'; 6 | const changePrompt = 'change prompt'; 7 | const changeAnswer = 'change answer'; 8 | 9 | describe('StackForm', () => { 10 | const stackForm = shallow(); 11 | 12 | it('renders the form title', () => { 13 | expect(stackForm.find('h4').at(1).text()).toEqual('Create a New Stack'); 14 | }); 15 | 16 | it('renders a link home', () => { 17 | expect(stackForm.find('h4').at(0).text()).toEqual('Home'); 18 | }); 19 | 20 | it('renders a Form component', () => { 21 | expect(stackForm.find('Form').exists()).toBe(true); 22 | }); 23 | 24 | it('renders a button to add a new card', () => { 25 | expect(stackForm.find('Button').at(0).props().children).toEqual('Add Card'); 26 | }); 27 | 28 | it('renders a button to submit the form', () => { 29 | expect(stackForm.find('Button').at(1).props().children).toEqual('Save and Add the Stack'); 30 | }); 31 | 32 | describe('and updating the title', () => { 33 | beforeEach(() => { 34 | stackForm.find('FormControl').simulate('change', { target: { value: changeTitle } }) 35 | }); 36 | 37 | it('updates the title in state', () => { 38 | expect(stackForm.state().title).toEqual(changeTitle); 39 | }); 40 | }); 41 | 42 | describe('when adding a new card', () => { 43 | beforeEach(() => { 44 | stackForm.find('Button').at(0).simulate('click'); 45 | }); 46 | 47 | afterEach(() => { 48 | stackForm.setState({ cards: [] }); 49 | }); 50 | 51 | it('adds a new card to the state', () => { 52 | expect(stackForm.state().cards.length).toEqual(1); 53 | }); 54 | 55 | it('renders the prompt section', () => { 56 | expect(stackForm.find('ControlLabel').at(1).props().children).toEqual('Prompt:'); 57 | }); 58 | 59 | it('renders the answer section', () => { 60 | expect(stackForm.find('ControlLabel').at(2).props().children).toEqual('Answer:'); 61 | }); 62 | 63 | describe('and updating the card prompt', () => { 64 | beforeEach(() => { 65 | stackForm.find('FormControl').at(1) 66 | .simulate('change', { target: { value: changePrompt } }); 67 | }); 68 | 69 | it('updates the prompt in the state', () => { 70 | expect(stackForm.state().cards[0].prompt).toEqual(changePrompt); 71 | }); 72 | }); 73 | 74 | describe('and updating the card answer', () => { 75 | beforeEach(() => { 76 | stackForm.find('FormControl').at(2) 77 | .simulate('change', { target: { value: changeAnswer }}); 78 | }); 79 | 80 | it('updates the answer in the state', () => { 81 | expect(stackForm.state().cards[0].answer).toEqual(changeAnswer); 82 | }); 83 | }); 84 | }); 85 | }); 86 | -------------------------------------------------------------------------------- /flashcardpro/src/components/StackList.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Link } from 'react-router-dom'; 4 | import stacks from '../data/stacks.json'; 5 | import { setStack, loadStacks } from '../actions'; 6 | 7 | export class StackList extends Component { 8 | componentDidMount() { 9 | if (this.props.stacks.length === 0) this.props.loadStacks(stacks); 10 | } 11 | 12 | render() { 13 | return ( 14 |
15 | { 16 | this.props.stacks.map(stack => { 17 | return ( 18 | this.props.setStack(stack)} 22 | > 23 |

{stack.title}

24 | 25 | ) 26 | }) 27 | } 28 |
29 | ) 30 | } 31 | } 32 | 33 | function mapStateToProps(state) { 34 | return { stacks: state.stacks }; 35 | } 36 | 37 | export default connect(mapStateToProps, { setStack, loadStacks })(StackList); -------------------------------------------------------------------------------- /flashcardpro/src/components/StackList.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import { StackList } from './StackList'; 4 | import { stacks } from '../data/fixtures'; 5 | 6 | const props = { stacks }; 7 | 8 | describe('StackList', () => { 9 | const stackList = shallow(); 10 | 11 | it('renders the correct number of links', () => { 12 | expect(stackList.find('Link').length).toEqual(props.stacks.length); 13 | }); 14 | }); -------------------------------------------------------------------------------- /flashcardpro/src/data/fixtures.js: -------------------------------------------------------------------------------- 1 | export const stack = { 2 | id: 0, 3 | title: 'test title', 4 | cards: [ 5 | { id: 0, prompt: 'test prompt', answer: 'test answer' }, 6 | { id: 1, prompt: 'test prompt 2', answer: 'test answer 2' } 7 | ] 8 | }; 9 | 10 | export const stacks = [stack]; -------------------------------------------------------------------------------- /flashcardpro/src/data/stacks.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "title": "State Abbreviations", 4 | "id": 0, 5 | "cards": [ 6 | { "id": 0, "prompt": "Arizona", "answer": "AZ" }, 7 | { "id": 1, "prompt": "California", "answer": "CA" }, 8 | { "id": 2, "prompt": "Hawaii", "answer": "HI" }, 9 | { "id": 3, "prompt": "Kansas", "answer": "KS" }, 10 | { "id": 4, "prompt": "Maryland", "answer": "MD" }, 11 | { "id": 5, "prompt": "Michigan", "answer": "MI" }, 12 | { "id": 6, "prompt": "New York", "answer": "NY" }, 13 | { "id": 7, "prompt": "Oregon", "answer": "OR" }, 14 | { "id": 8, "prompt": "Texas", "answer": "TX" }, 15 | { "id": 9, "prompt": "Washington", "answer": "WA" } 16 | ] 17 | }, 18 | { 19 | "title": "Computer Science Basics", 20 | "id": 1, 21 | "cards": [ 22 | { "id": 0, "prompt": "A single line of code", "answer": "statement" }, 23 | { "id": 1, "prompt": "A word reserved to store data", "answer": "variable" }, 24 | { "id": 2, "prompt": "A storage component to serve requests faster", "answer": "cache" }, 25 | { "id": 3, "prompt": "Where data is stored", "answer": "memory" }, 26 | { "id": 4, "prompt": "8 bits =", "answer": "1 byte" }, 27 | { "id": 5, "prompt": "A way to repeat code a certain number of times", "answer": "loop" }, 28 | { "id": 6, "prompt": "UI stands for", "answer": "User Interface" } 29 | ] 30 | } 31 | ] 32 | -------------------------------------------------------------------------------- /flashcardpro/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 5%; 3 | text-align: center; 4 | } 5 | 6 | .link-home { 7 | position: absolute; 8 | left: 30px; 9 | top: 30px; 10 | } 11 | 12 | .card { 13 | border: 1px solid lightgray; 14 | border-radius: 5px; 15 | margin: 10px; 16 | padding: 10px; 17 | font-size: 16px; 18 | cursor: pointer; 19 | } 20 | 21 | .card-prompt { 22 | display: inline-block; 23 | text-align: left; 24 | width: 50%; 25 | } 26 | 27 | .card-answer { 28 | display: inline-block; 29 | text-align: right; 30 | width: 50%; 31 | } 32 | 33 | .text-hidden { 34 | visibility: hidden; 35 | } 36 | 37 | .text-revealed { 38 | animation-name: fade-in; 39 | animation-duration: 1s; 40 | visibility: visible; 41 | } 42 | 43 | @keyframes fade-in { 44 | from { opacity: 0 } 45 | to { opacity: 100 } 46 | } -------------------------------------------------------------------------------- /flashcardpro/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import { createStore } from 'redux'; 4 | import { BrowserRouter, Switch, Route } from 'react-router-dom'; 5 | import { Provider } from 'react-redux'; 6 | import rootReducer from './reducers'; 7 | import App from './components/App'; 8 | import Stack from './components/Stack'; 9 | import StackForm from './components/StackForm'; 10 | import { setStack } from './actions'; 11 | import './index.css'; 12 | 13 | const store = createStore(rootReducer); 14 | store.subscribe(() => console.log('store', store.getState())); 15 | store.dispatch(setStack({ id: 0, title: 'example', cards: [] })); 16 | 17 | ReactDOM.render( 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | , 27 | document.getElementById('root') 28 | ); -------------------------------------------------------------------------------- /flashcardpro/src/reducers/index.js: -------------------------------------------------------------------------------- 1 | import { combineReducers } from 'redux'; 2 | import { SET_STACK, LOAD_STACKS, ADD_STACK } from '../actions'; 3 | 4 | function stack(state = {}, action) { 5 | switch (action.type) { 6 | case SET_STACK: 7 | return action.stack; 8 | default: 9 | return state; 10 | } 11 | } 12 | 13 | function stacks(state = [], action) { 14 | switch(action.type) { 15 | case LOAD_STACKS: 16 | return action.stacks; 17 | case ADD_STACK: 18 | return [...state, {...action.stack, id: state.length }]; 19 | default: 20 | return state; 21 | } 22 | } 23 | 24 | export default combineReducers({ stack, stacks }); -------------------------------------------------------------------------------- /flashcardpro/src/reducers/index.test.js: -------------------------------------------------------------------------------- 1 | import rootReducer from './index'; 2 | import * as actions from '../actions'; 3 | import { stack, stacks } from '../data/fixtures'; 4 | 5 | describe('root reducer', () => { 6 | it('returns the initial state', () => { 7 | expect(rootReducer({}, {})).toEqual({ stack: {}, stacks: [] }); 8 | }); 9 | 10 | it('sets the main stack', () => { 11 | expect(rootReducer({}, { type: actions.SET_STACK, stack })) 12 | .toEqual({ stack, stacks: [] }); 13 | }); 14 | 15 | it('loads stacks', () => { 16 | expect(rootReducer({}, { type: actions.LOAD_STACKS, stacks})) 17 | .toEqual({ stack: {}, stacks }); 18 | }); 19 | 20 | it('adds a stack', () => { 21 | const testStack = { title: 'data', cards: [] }; 22 | 23 | expect(rootReducer({}, { type: actions.ADD_STACK, stack: testStack })) 24 | .toEqual({ stack: {}, stacks: [{...testStack, id: 0}] }); 25 | }); 26 | }); -------------------------------------------------------------------------------- /flashcardpro_parcel/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://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.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /flashcardpro_parcel/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 22 | 23 | 24 | React App 25 | 26 | 27 | 30 |
31 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /flashcardpro_parcel/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "flashcardpro", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "start": "react-scripts start", 7 | "build": "react-scripts build", 8 | "test": "react-scripts test --env=jsdom", 9 | "eject": "react-scripts eject" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /flashcardpro_parcel/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/15Dkatz/react-testing/66f64b5d55e48b7f5930f137dd568a0d9305d27e/flashcardpro_parcel/public/favicon.ico -------------------------------------------------------------------------------- /flashcardpro_parcel/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "192x192", 8 | "type": "image/png" 9 | } 10 | ], 11 | "start_url": "./index.html", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /flashcardpro_parcel/src/actions/index.js: -------------------------------------------------------------------------------- 1 | export const SET_STACK = 'SET_STACK'; 2 | export const LOAD_STACKS = 'LOAD_STACKS'; 3 | export const ADD_STACK = 'ADD_STACK'; 4 | 5 | export function setStack(stack) { 6 | return { 7 | type: SET_STACK, 8 | stack 9 | }; 10 | } 11 | 12 | export function loadStacks(stacks) { 13 | return { 14 | type: LOAD_STACKS, 15 | stacks 16 | } 17 | } 18 | 19 | export function addStack(stack) { 20 | return { 21 | type: ADD_STACK, 22 | stack 23 | } 24 | } -------------------------------------------------------------------------------- /flashcardpro_parcel/src/actions/index.test.js: -------------------------------------------------------------------------------- 1 | import * as actions from './index'; 2 | import { stack, stacks } from '../data/fixtures'; 3 | 4 | describe('actions', () => { 5 | it('creates an action to set the main stack', () => { 6 | const expectedAction = { type: actions.SET_STACK, stack }; 7 | 8 | expect(actions.setStack(stack)).toEqual(expectedAction); 9 | }); 10 | 11 | it('creates an action to add a stack', () => { 12 | const expectedAction = { type: actions.ADD_STACK, stack }; 13 | 14 | expect(actions.addStack(stack)).toEqual(expectedAction); 15 | }); 16 | 17 | it('creates an action to load stacks', () => { 18 | const expectedAction = { type: actions.LOAD_STACKS, stacks }; 19 | 20 | expect(actions.loadStacks(stacks)).toEqual(expectedAction); 21 | }); 22 | }); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { Link } from 'react-router-dom'; 3 | import StackList from './StackList'; 4 | 5 | const App = () => { 6 | return ( 7 |
8 |

Flashcard Pro

9 |
10 | 11 |
12 |

Create a New Stack

13 |
14 | ) 15 | } 16 | 17 | export default App; -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import App from './App'; 4 | 5 | describe('App', () => { 6 | const app = shallow(); 7 | 8 | it('renders the `Flashcard Pro` title', () => { 9 | expect(app.find('h2').text()).toEqual('Flashcard Pro') 10 | }); 11 | 12 | it('renders the StackList', () => { 13 | expect(app.find('Connect(StackList)').exists()).toBe(true); 14 | }); 15 | 16 | it('renders a link to create new stacks', () => { 17 | expect(app.find('Link h4').text()).toEqual('Create a New Stack'); 18 | }); 19 | }); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/Card.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | 3 | class Card extends Component { 4 | constructor() { 5 | super(); 6 | 7 | this.state = { reveal: false }; 8 | } 9 | 10 | render() { 11 | const { prompt, answer } = this.props.card; 12 | 13 | return ( 14 |
this.setState({ reveal: true })}> 15 |
16 |

{prompt}

17 |
18 |
19 |

20 | {answer} 21 |

22 |
23 |
24 | ) 25 | } 26 | } 27 | 28 | export default Card; -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/Card.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import Card from './Card'; 4 | 5 | const props = { 6 | card: { prompt: 'test prompt', answer: 'test answer'} 7 | }; 8 | 9 | describe('Card', () => { 10 | const card = shallow(); 11 | 12 | it('sets `reveal` to be `false`', () => { 13 | expect(card.state().reveal).toBe(false); 14 | }); 15 | 16 | it('renders the card prompt', () => { 17 | expect(card.find('.card-prompt h4').text()).toEqual(props.card.prompt); 18 | }); 19 | 20 | it('renders the card answer', () => { 21 | expect(card.find('.card-answer h4').text()).toEqual(props.card.answer); 22 | }); 23 | 24 | it('applies the `text-hidden` class to the card answer', () => { 25 | expect(card.find('.card-answer h4').hasClass('text-hidden')).toBe(true); 26 | }); 27 | 28 | describe('when clicking on the card', () => { 29 | beforeEach(() => card.simulate('click')); 30 | 31 | it('updates `reveal` to be `true`', () => { 32 | expect(card.state().reveal).toBe(true); 33 | }); 34 | 35 | it('applies the `text-revealed` class to the card answer', () => { 36 | expect(card.find('.card-answer h4').hasClass('text-revealed')).toBe(true); 37 | }); 38 | }); 39 | }); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/Stack.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Link } from 'react-router-dom'; 4 | import Card from './Card'; 5 | 6 | export const Stack = ({ stack: { title, cards } }) => { 7 | return ( 8 |
9 | 10 |

Home

11 | 12 |

{title}

13 |
14 | { 15 | cards.map(card => { 16 | return ( 17 | 18 | ) 19 | }) 20 | } 21 |
22 | ) 23 | } 24 | 25 | function mapStateToProps(state) { 26 | return { stack: state.stack }; 27 | } 28 | 29 | export default connect(mapStateToProps, null)(Stack); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/Stack.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import { Stack } from './Stack'; 4 | import { stack } from '../data/fixtures'; 5 | 6 | const props = { stack }; 7 | 8 | describe('Stack', () => { 9 | const stack = shallow(); 10 | 11 | it('renders the title', () => { 12 | expect(stack.find('h3').text()).toEqual(props.stack.title); 13 | }); 14 | 15 | it('renders the Link home', () => { 16 | expect(stack.find('Link h4').text()).toEqual('Home'); 17 | }); 18 | 19 | it('renders the correct number of cards', () => { 20 | expect(stack.find('Card').length).toEqual(props.stack.cards.length); 21 | }); 22 | }); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/StackForm.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Link } from 'react-router-dom'; 4 | import { Form, FormGroup, FormControl, ControlLabel, Button } from 'react-bootstrap'; 5 | import { addStack } from '../actions'; 6 | 7 | export class StackForm extends Component { 8 | constructor() { 9 | super(); 10 | 11 | this.state = { 12 | title: '', 13 | cards: [] 14 | } 15 | } 16 | 17 | addCard() { 18 | const { cards } = this.state; 19 | 20 | cards.push({ id: cards.length, prompt: '', answer: '' }); 21 | 22 | this.setState({ cards }); 23 | } 24 | 25 | updateCardPart(event, index, part) { 26 | const { cards } = this.state; 27 | 28 | cards[index][part] = event.target.value; 29 | 30 | this.setState({ cards }); 31 | } 32 | 33 | addStack() { 34 | this.props.addStack(this.state); 35 | } 36 | 37 | render() { 38 | return ( 39 |
40 | 41 |

Home

42 | 43 |

Create a New Stack

44 |
45 |
46 | 47 | Title: 48 | {' '} 49 | this.setState({ title: event.target.value })} /> 50 | 51 | { 52 | this.state.cards.map((card, index) => { 53 | return ( 54 |
55 |
56 | 57 | Prompt: 58 | {' '} 59 | this.updateCardPart(event, index, 'prompt')} 61 | /> 62 | {' '} 63 | Answer: 64 | {' '} 65 | this.updateCardPart(event, index, 'answer')} 67 | /> 68 | 69 |
70 | ) 71 | }) 72 | } 73 |
74 |
75 | 76 | {' '} 77 | 78 |
79 | ) 80 | } 81 | } 82 | 83 | export default connect(null, { addStack })(StackForm); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/StackForm.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import { StackForm } from './StackForm'; 4 | 5 | const changeTitle = 'change title'; 6 | const changePrompt = 'change prompt'; 7 | const changeAnswer = 'change answer'; 8 | 9 | describe('StackForm', () => { 10 | const stackForm = shallow(); 11 | 12 | it('renders the form title', () => { 13 | expect(stackForm.find('h4').at(1).text()).toEqual('Create a New Stack'); 14 | }); 15 | 16 | it('renders a link home', () => { 17 | expect(stackForm.find('h4').at(0).text()).toEqual('Home'); 18 | }); 19 | 20 | it('renders a Form component', () => { 21 | expect(stackForm.find('Form').exists()).toBe(true); 22 | }); 23 | 24 | it('renders a button to add a new card', () => { 25 | expect(stackForm.find('Button').at(0).props().children).toEqual('Add Card'); 26 | }); 27 | 28 | it('renders a button to submit the form', () => { 29 | expect(stackForm.find('Button').at(1).props().children).toEqual('Save and Add the Stack'); 30 | }); 31 | 32 | describe('and updating the title', () => { 33 | beforeEach(() => { 34 | stackForm.find('FormControl').simulate('change', { target: { value: changeTitle } }) 35 | }); 36 | 37 | it('updates the title in state', () => { 38 | expect(stackForm.state().title).toEqual(changeTitle); 39 | }); 40 | }); 41 | 42 | describe('when adding a new card', () => { 43 | beforeEach(() => { 44 | stackForm.find('Button').at(0).simulate('click'); 45 | }); 46 | 47 | afterEach(() => { 48 | stackForm.setState({ cards: [] }); 49 | }); 50 | 51 | it('adds a new card to the state', () => { 52 | expect(stackForm.state().cards.length).toEqual(1); 53 | }); 54 | 55 | it('renders the prompt section', () => { 56 | expect(stackForm.find('ControlLabel').at(1).props().children).toEqual('Prompt:'); 57 | }); 58 | 59 | it('renders the answer section', () => { 60 | expect(stackForm.find('ControlLabel').at(2).props().children).toEqual('Answer:'); 61 | }); 62 | 63 | describe('and updating the card prompt', () => { 64 | beforeEach(() => { 65 | stackForm.find('FormControl').at(1) 66 | .simulate('change', { target: { value: changePrompt } }); 67 | }); 68 | 69 | it('updates the prompt in the state', () => { 70 | expect(stackForm.state().cards[0].prompt).toEqual(changePrompt); 71 | }); 72 | }); 73 | 74 | describe('and updating the card answer', () => { 75 | beforeEach(() => { 76 | stackForm.find('FormControl').at(2) 77 | .simulate('change', { target: { value: changeAnswer }}); 78 | }); 79 | 80 | it('updates the answer in the state', () => { 81 | expect(stackForm.state().cards[0].answer).toEqual(changeAnswer); 82 | }); 83 | }); 84 | }); 85 | }); 86 | -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/StackList.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Link } from 'react-router-dom'; 4 | import stacks from '../data/stacks.json'; 5 | import { setStack, loadStacks } from '../actions'; 6 | 7 | export class StackList extends Component { 8 | componentDidMount() { 9 | if (this.props.stacks.length === 0) this.props.loadStacks(stacks); 10 | } 11 | 12 | render() { 13 | return ( 14 |
15 | { 16 | this.props.stacks.map(stack => { 17 | return ( 18 | this.props.setStack(stack)} 22 | > 23 |

{stack.title}

24 | 25 | ) 26 | }) 27 | } 28 |
29 | ) 30 | } 31 | } 32 | 33 | function mapStateToProps(state) { 34 | return { stacks: state.stacks }; 35 | } 36 | 37 | export default connect(mapStateToProps, { setStack, loadStacks })(StackList); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/components/StackList.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import { StackList } from './StackList'; 4 | import { stacks } from '../data/fixtures'; 5 | 6 | const props = { stacks }; 7 | 8 | describe('StackList', () => { 9 | const stackList = shallow(); 10 | 11 | it('renders the correct number of links', () => { 12 | expect(stackList.find('Link').length).toEqual(props.stacks.length); 13 | }); 14 | }); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/data/fixtures.js: -------------------------------------------------------------------------------- 1 | export const stack = { 2 | id: 0, 3 | title: 'test title', 4 | cards: [ 5 | { id: 0, prompt: 'test prompt', answer: 'test answer' }, 6 | { id: 1, prompt: 'test prompt 2', answer: 'test answer 2' } 7 | ] 8 | }; 9 | 10 | export const stacks = [stack]; -------------------------------------------------------------------------------- /flashcardpro_parcel/src/data/stacks.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "title": "State Abbreviations", 4 | "id": 0, 5 | "cards": [ 6 | { "id": 0, "prompt": "Arizona", "answer": "AR" }, 7 | { "id": 1, "prompt": "California", "answer": "CA" }, 8 | { "id": 2, "prompt": "Hawaii", "answer": "HI" }, 9 | { "id": 3, "prompt": "Kansas", "answer": "KS" }, 10 | { "id": 4, "prompt": "Maryland", "answer": "MD" }, 11 | { "id": 5, "prompt": "Michigan", "answer": "MI" }, 12 | { "id": 6, "prompt": "New York", "answer": "NY" }, 13 | { "id": 7, "prompt": "Oregon", "answer": "OR" }, 14 | { "id": 8, "prompt": "Texas", "answer": "TX" }, 15 | { "id": 9, "prompt": "Washington", "answer": "WA" } 16 | ] 17 | }, 18 | { 19 | "title": "Computer Science Basics", 20 | "id": 1, 21 | "cards": [ 22 | { "id": 0, "prompt": "A single line of code", "answer": "statement" }, 23 | { "id": 1, "prompt": "A word reserved to store data", "answer": "variable" }, 24 | { "id": 2, "prompt": "A storage component to serve requests faster", "answer": "cache" }, 25 | { "id": 3, "prompt": "Where data is stored", "answer": "memory" }, 26 | { "id": 4, "prompt": "8 bits =", "answer": "1 byte" }, 27 | { "id": 5, "prompt": "A way to repeat code a certain number of times", "answer": "loop" }, 28 | { "id": 6, "prompt": "UI stands for", "answer": "User Interface" } 29 | ] 30 | } 31 | ] 32 | -------------------------------------------------------------------------------- /flashcardpro_parcel/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 5%; 3 | text-align: center; 4 | } 5 | 6 | .link-home { 7 | position: absolute; 8 | left: 30px; 9 | top: 30px; 10 | } 11 | 12 | .card { 13 | border: 1px solid lightgray; 14 | border-radius: 5px; 15 | margin: 10px; 16 | padding: 10px; 17 | font-size: 16px; 18 | cursor: pointer; 19 | } 20 | 21 | .card-prompt { 22 | display: inline-block; 23 | text-align: left; 24 | width: 50%; 25 | } 26 | 27 | .card-answer { 28 | display: inline-block; 29 | text-align: right; 30 | width: 50%; 31 | } 32 | 33 | .text-hidden { 34 | visibility: hidden; 35 | } 36 | 37 | .text-revealed { 38 | animation-name: fade-in; 39 | animation-duration: 1s; 40 | visibility: visible; 41 | } 42 | 43 | @keyframes fade-in { 44 | from { opacity: 0 } 45 | to { opacity: 100 } 46 | } -------------------------------------------------------------------------------- /flashcardpro_parcel/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import { createStore } from 'redux'; 4 | import { BrowserRouter, Switch, Route } from 'react-router-dom'; 5 | import { Provider } from 'react-redux'; 6 | import rootReducer from './reducers'; 7 | import App from './components/App'; 8 | import Stack from './components/Stack'; 9 | import StackForm from './components/StackForm'; 10 | import { setStack } from './actions'; 11 | import './index.css'; 12 | 13 | const store = createStore(rootReducer); 14 | store.subscribe(() => console.log('store', store.getState())); 15 | store.dispatch(setStack({ id: 0, title: 'example', cards: [] })); 16 | 17 | ReactDOM.render( 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | , 27 | document.getElementById('root') 28 | ); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/reducers/index.js: -------------------------------------------------------------------------------- 1 | import { combineReducers } from 'redux'; 2 | import { SET_STACK, LOAD_STACKS, ADD_STACK } from '../actions'; 3 | 4 | function stack(state = {}, action) { 5 | switch (action.type) { 6 | case SET_STACK: 7 | return action.stack; 8 | default: 9 | return state; 10 | } 11 | } 12 | 13 | function stacks(state = [], action) { 14 | switch(action.type) { 15 | case LOAD_STACKS: 16 | return action.stacks; 17 | case ADD_STACK: 18 | return [...state, {...action.stack, id: state.length }]; 19 | default: 20 | return state; 21 | } 22 | } 23 | 24 | export default combineReducers({ stack, stacks }); -------------------------------------------------------------------------------- /flashcardpro_parcel/src/reducers/index.test.js: -------------------------------------------------------------------------------- 1 | import rootReducer from './index'; 2 | import * as actions from '../actions'; 3 | import { stack, stacks } from '../data/fixtures'; 4 | 5 | describe('root reducer', () => { 6 | it('returns the initial state', () => { 7 | expect(rootReducer({}, {})).toEqual({ stack: {}, stacks: [] }); 8 | }); 9 | 10 | it('sets the main stack', () => { 11 | expect(rootReducer({}, { type: actions.SET_STACK, stack })) 12 | .toEqual({ stack, stacks: [] }); 13 | }); 14 | 15 | it('loads stacks', () => { 16 | expect(rootReducer({}, { type: actions.LOAD_STACKS, stacks})) 17 | .toEqual({ stack: {}, stacks }); 18 | }); 19 | 20 | it('adds a stack', () => { 21 | const testStack = { title: 'data', cards: [] }; 22 | 23 | expect(rootReducer({}, { type: actions.ADD_STACK, stack: testStack })) 24 | .toEqual({ stack: {}, stacks: [{...testStack, id: 0}] }); 25 | }); 26 | }); -------------------------------------------------------------------------------- /jeopardy/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://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.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /jeopardy/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jeopardy", 3 | "version": "0.1.0", 4 | "private": true, 5 | "devDependencies": { 6 | "enzyme": "^2.9.1", 7 | "react-scripts": "1.0.11", 8 | "react-test-renderer": "^15.6.1", 9 | "sinon": "^3.2.0" 10 | }, 11 | "dependencies": { 12 | "react": "^15.6.1", 13 | "react-bootstrap": "^0.31.2", 14 | "react-dom": "^15.6.1", 15 | "react-redux": "^5.0.6", 16 | "react-router-dom": "^4.1.2", 17 | "redux": "^3.7.2" 18 | }, 19 | "scripts": { 20 | "start": "react-scripts start", 21 | "build": "react-scripts build", 22 | "test": "react-scripts test --env=jsdom", 23 | "eject": "react-scripts eject" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /jeopardy/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/15Dkatz/react-testing/66f64b5d55e48b7f5930f137dd568a0d9305d27e/jeopardy/public/favicon.ico -------------------------------------------------------------------------------- /jeopardy/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 22 | 23 | 24 | React App 25 | 26 | 27 | 30 |
31 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /jeopardy/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "192x192", 8 | "type": "image/png" 9 | } 10 | ], 11 | "start_url": "./index.html", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /jeopardy/src/actions/index.js: -------------------------------------------------------------------------------- 1 | export const SET_CATEGORIES = 'SET_CATEGORIES'; 2 | export const PICK_CATEGORY = 'PICK_CATEGORY'; 3 | 4 | export function setCategories(categories) { 5 | return { 6 | type: SET_CATEGORIES, 7 | categories 8 | } 9 | } 10 | 11 | export function pickCategory(category) { 12 | return { 13 | type: PICK_CATEGORY, 14 | category 15 | } 16 | } -------------------------------------------------------------------------------- /jeopardy/src/actions/index.test.js: -------------------------------------------------------------------------------- 1 | import * as actions from './index'; 2 | import { categories, category } from '../data/fixtures'; 3 | 4 | describe('actions', () => { 5 | it('creates an action to set categories', () => { 6 | const expectedAction = { 7 | type: actions.SET_CATEGORIES, 8 | categories 9 | }; 10 | 11 | expect(actions.setCategories(categories)).toEqual(expectedAction); 12 | }); 13 | 14 | it('creates an action to pick a category', () => { 15 | const expectedAction = { 16 | type: actions.PICK_CATEGORY, 17 | category 18 | }; 19 | 20 | expect(actions.pickCategory(category)).toEqual(expectedAction); 21 | }); 22 | }); -------------------------------------------------------------------------------- /jeopardy/src/components/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Link } from 'react-router-dom'; 4 | import { setCategories, pickCategory } from '../actions'; 5 | 6 | export class App extends Component { 7 | componentDidMount() { 8 | if (this.props.categories.length === 0) { 9 | fetch('http://jservice.io/api/categories?count=20') 10 | .then(response => response.json()) 11 | .then(json => this.props.setCategories(json)); 12 | } 13 | } 14 | 15 | render() { 16 | // console.log('App props', this.props); 17 | 18 | return ( 19 |
20 |

Jeopardy!

21 | { 22 | this.props.categories.map(category => { 23 | return ( 24 |
25 | this.props.pickCategory(category)} 28 | > 29 |

{category.title}

30 | 31 |
32 | ) 33 | }) 34 | } 35 |
36 | ) 37 | } 38 | } 39 | 40 | function mapStateToProps(state) { 41 | return { categories: state.categories } 42 | } 43 | 44 | export default connect(mapStateToProps, { setCategories, pickCategory })(App); -------------------------------------------------------------------------------- /jeopardy/src/components/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import { App } from './App'; 4 | import { categories } from '../data/fixtures'; 5 | 6 | const props = { categories }; 7 | 8 | describe('App', () => { 9 | const app = shallow(); 10 | 11 | it('renders the title', () => { 12 | expect(app.find('h2').text()).toEqual('Jeopardy!'); 13 | }); 14 | 15 | it('creates the correct number of links', () => { 16 | expect(app.find('Link').length).toEqual(categories.length); 17 | }); 18 | 19 | it('title the links correctly', () => { 20 | app.find('Link h4').forEach((linkTitle, index) => { 21 | expect(linkTitle.text()).toEqual(categories[index].title); 22 | }); 23 | }); 24 | }); -------------------------------------------------------------------------------- /jeopardy/src/components/Category.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { Link } from 'react-router-dom'; 4 | import Clue from './Clue'; 5 | 6 | export class Category extends Component { 7 | constructor() { 8 | super(); 9 | 10 | this.state = { clues: [] }; 11 | } 12 | 13 | componentDidMount() { 14 | fetch(`http://jservice.io/api/clues?category=${this.props.category.id}`) 15 | .then(response => response.json()) 16 | .then(json => this.setState({ clues: json })); 17 | } 18 | 19 | render() { 20 | // console.log('category props', this.props); 21 | 22 | return ( 23 |
24 |

{this.props.category.title}

25 | { 26 | this.state.clues.map(clue => { 27 | return ( 28 | 29 | ) 30 | }) 31 | } 32 |
33 | ) 34 | } 35 | } 36 | 37 | export class LinkedCategory extends Component { 38 | render() { 39 | return ( 40 |
41 |

Home

42 | 43 |
44 | ) 45 | } 46 | } 47 | 48 | function mapStateToProps(state) { 49 | return { category: state.category } 50 | } 51 | 52 | export default connect(mapStateToProps, null)(LinkedCategory); -------------------------------------------------------------------------------- /jeopardy/src/components/Category.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { mount, shallow } from 'enzyme'; 3 | import { Category, LinkedCategory } from './Category'; 4 | import { categories, clues } from '../data/fixtures'; 5 | import { fakeServer } from 'sinon'; 6 | 7 | const props = { category: categories[0] }; 8 | 9 | describe('Category', () => { 10 | let server; 11 | 12 | beforeEach(() => { 13 | server = fakeServer.create(); 14 | 15 | server.respondWith( 16 | 'GET', 17 | `http://jservice.io/api/clues?category=${props.category.id}`, 18 | [ 19 | 200, 20 | { 'Content-Type': 'application/json' }, 21 | JSON.stringify(clues) 22 | ] 23 | ); 24 | }); 25 | 26 | describe('when creating a new category', () => { 27 | let category; 28 | 29 | beforeEach(done => { 30 | category = mount(); 31 | 32 | server.respond(); 33 | 34 | setTimeout(done); 35 | }); 36 | 37 | // it('logs the category', () => { 38 | // console.log(category.debug()); 39 | // }); 40 | 41 | it('initializes the clues in state', () => { 42 | expect(category.state().clues).toEqual(clues); 43 | }); 44 | 45 | it('renders the category title', () => { 46 | expect(category.find('h2').text()).toEqual(props.category.title); 47 | }); 48 | 49 | it('renders the correct number of clues', () => { 50 | expect(category.find('Clue').length).toEqual(clues.length); 51 | }); 52 | }); 53 | }); 54 | 55 | describe('LinkedCategory', () => { 56 | const linkedCategory = shallow(); 57 | 58 | it('creates the link to navigate home', () => { 59 | expect(linkedCategory.find('Link h4').text()).toEqual('Home'); 60 | }); 61 | 62 | it('creates a category component', () => { 63 | expect(linkedCategory.find('Category').exists()).toBe(true); 64 | }); 65 | }); -------------------------------------------------------------------------------- /jeopardy/src/components/Clue.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | 3 | class Clue extends Component { 4 | constructor() { 5 | super(); 6 | 7 | this.state = { reveal: false } 8 | } 9 | 10 | render() { 11 | const { answer, question, value } = this.props.clue; 12 | 13 | return ( 14 |
this.setState({ reveal: true })}> 15 |

{value || 'unknown'}

16 |
17 |
{question}
18 |
19 |
20 | {answer} 21 |
22 |
23 | ) 24 | } 25 | } 26 | 27 | export default Clue; -------------------------------------------------------------------------------- /jeopardy/src/components/Clue.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { shallow } from 'enzyme'; 3 | import Clue from './Clue'; 4 | import { clue } from '../data/fixtures'; 5 | 6 | const props = { clue }; 7 | 8 | describe('Clue', () => { 9 | let clueWrapper = shallow(); 10 | 11 | it('renders the clue value', () => { 12 | // console.log(clueWrapper.debug()); 13 | expect(clueWrapper.find('h4').text()).toEqual(clue.value.toString()); 14 | }); 15 | 16 | it('renders the clue question', () => { 17 | expect(clueWrapper.find('h5').at(0).text()).toEqual(clue.question); 18 | }); 19 | 20 | it('renders the clue answer', () => { 21 | expect(clueWrapper.find('h5').at(1).text()).toEqual(clue.answer); 22 | }); 23 | 24 | it('sets the answer with the `text-hidden` class', () => { 25 | expect(clueWrapper.find('h5').at(1).hasClass('text-hidden')).toBe(true); 26 | }); 27 | 28 | it('initializes the `reveal` state to be `false`', () => { 29 | expect(clueWrapper.state().reveal).toBe(false); 30 | }); 31 | 32 | describe('when rendering a clue with no value', () => { 33 | beforeEach(() => { 34 | props.clue.value = undefined; 35 | 36 | clueWrapper = shallow(); 37 | }); 38 | 39 | it('displays the value as `unknown`', () => { 40 | expect(clueWrapper.find('h4').text()).toEqual('unknown'); 41 | }); 42 | }); 43 | 44 | describe('when clicking on the clue', () => { 45 | beforeEach(() => clueWrapper.simulate('click')); 46 | 47 | it('sets the `reveal` state to be `true`', () => { 48 | expect(clueWrapper.state().reveal).toBe(true); 49 | }); 50 | 51 | it('sets the answer with the `text-revealed` class', () => { 52 | expect(clueWrapper.find('h5').at(1).hasClass('text-revealed')).toBe(true); 53 | }); 54 | }); 55 | }); -------------------------------------------------------------------------------- /jeopardy/src/data/fixtures.js: -------------------------------------------------------------------------------- 1 | export const categories = [ 2 | { id: 0, title: 'category one' }, 3 | { id: 1, title: 'category two' }, 4 | { id: 2, title: 'category three' } 5 | ]; 6 | 7 | export const category = categories[0]; 8 | 9 | export const clue = { 10 | id: 0, 11 | question: 'q one', 12 | answer: 'a one', 13 | value: 200 14 | }; 15 | 16 | export const clues = [ 17 | clue, 18 | { id: 1, question: 'q two', answer: 'a two', value: 400 } 19 | ]; -------------------------------------------------------------------------------- /jeopardy/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding: 5%; 3 | text-align: center; 4 | } 5 | 6 | .link-home { 7 | position: absolute; 8 | left: 30px; 9 | top: 30px; 10 | } 11 | 12 | .clue { 13 | border: 1px solid lightgray; 14 | border-radius: 5px; 15 | margin: 10px; 16 | padding: 10px; 17 | cursor: pointer; 18 | } 19 | 20 | .text-hidden { 21 | visibility: hidden; 22 | } 23 | 24 | .text-revealed { 25 | animation-name: fade-in; 26 | animation-duration: 1s; 27 | visibility: visible; 28 | } 29 | 30 | @keyframes fade-in { 31 | from { opacity: 0 } 32 | to { opacity: 100 } 33 | } -------------------------------------------------------------------------------- /jeopardy/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import { Provider } from 'react-redux'; 4 | import { createStore } from 'redux'; 5 | import { BrowserRouter, Switch, Route } from 'react-router-dom'; 6 | import rootReducer from './reducers'; 7 | import App from './components/App'; 8 | import Category from './components/Category'; 9 | import './index.css'; 10 | 11 | const store = createStore(rootReducer); 12 | 13 | ReactDOM.render( 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | , 22 | document.getElementById('root') 23 | ); -------------------------------------------------------------------------------- /jeopardy/src/reducers/index.js: -------------------------------------------------------------------------------- 1 | import { combineReducers } from 'redux'; 2 | import { SET_CATEGORIES, PICK_CATEGORY } from '../actions'; 3 | 4 | function categories(state = [], action) { 5 | switch(action.type) { 6 | case SET_CATEGORIES: 7 | return action.categories; 8 | default: 9 | return state; 10 | } 11 | } 12 | 13 | function category(state = {}, action) { 14 | switch(action.type) { 15 | case PICK_CATEGORY: 16 | return action.category; 17 | default: 18 | return state; 19 | } 20 | } 21 | 22 | export default combineReducers({ categories, category }); -------------------------------------------------------------------------------- /jeopardy/src/reducers/index.test.js: -------------------------------------------------------------------------------- 1 | import rootReducer from './index'; 2 | import * as actions from '../actions'; 3 | import { categories, category } from '../data/fixtures'; 4 | 5 | describe('root reducer', () => { 6 | it('returns the initial state', () => { 7 | expect(rootReducer({}, {})).toEqual({ categories: [], category: {} }); 8 | }); 9 | 10 | it('sets categories', () => { 11 | expect(rootReducer({}, { type: actions.SET_CATEGORIES, categories })) 12 | .toEqual({ categories, category: {} }); 13 | }); 14 | 15 | it('picks a category', () => { 16 | expect(rootReducer({}, { type: actions.PICK_CATEGORY, category })) 17 | .toEqual({ categories: [], category }); 18 | }); 19 | }); -------------------------------------------------------------------------------- /notetoself/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://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.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /notetoself/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 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) 17 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 18 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 19 | - [Debugging in the Editor](#debugging-in-the-editor) 20 | - [Formatting Code Automatically](#formatting-code-automatically) 21 | - [Changing the Page ``](#changing-the-page-title) 22 | - [Installing a Dependency](#installing-a-dependency) 23 | - [Importing a Component](#importing-a-component) 24 | - [Code Splitting](#code-splitting) 25 | - [Adding a Stylesheet](#adding-a-stylesheet) 26 | - [Post-Processing CSS](#post-processing-css) 27 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) 28 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) 29 | - [Using the `public` Folder](#using-the-public-folder) 30 | - [Changing the HTML](#changing-the-html) 31 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 32 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 33 | - [Using Global Variables](#using-global-variables) 34 | - [Adding Bootstrap](#adding-bootstrap) 35 | - [Using a Custom Theme](#using-a-custom-theme) 36 | - [Adding Flow](#adding-flow) 37 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 38 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 39 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 40 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 41 | - [Can I Use Decorators?](#can-i-use-decorators) 42 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 43 | - [Node](#node) 44 | - [Ruby on Rails](#ruby-on-rails) 45 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 46 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) 47 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually) 48 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy) 49 | - [Using HTTPS in Development](#using-https-in-development) 50 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 51 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 52 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 53 | - [Running Tests](#running-tests) 54 | - [Filename Conventions](#filename-conventions) 55 | - [Command Line Interface](#command-line-interface) 56 | - [Version Control Integration](#version-control-integration) 57 | - [Writing Tests](#writing-tests) 58 | - [Testing Components](#testing-components) 59 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 60 | - [Initializing Test Environment](#initializing-test-environment) 61 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 62 | - [Coverage Reporting](#coverage-reporting) 63 | - [Continuous Integration](#continuous-integration) 64 | - [Disabling jsdom](#disabling-jsdom) 65 | - [Snapshot Testing](#snapshot-testing) 66 | - [Editor Integration](#editor-integration) 67 | - [Developing Components in Isolation](#developing-components-in-isolation) 68 | - [Getting Started with Storybook](#getting-started-with-storybook) 69 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist) 70 | - [Making a Progressive Web App](#making-a-progressive-web-app) 71 | - [Offline-First Considerations](#offline-first-considerations) 72 | - [Progressive Web App Metadata](#progressive-web-app-metadata) 73 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size) 74 | - [Deployment](#deployment) 75 | - [Static Server](#static-server) 76 | - [Other Solutions](#other-solutions) 77 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 78 | - [Building for Relative Paths](#building-for-relative-paths) 79 | - [Azure](#azure) 80 | - [Firebase](#firebase) 81 | - [GitHub Pages](#github-pages) 82 | - [Heroku](#heroku) 83 | - [Modulus](#modulus) 84 | - [Netlify](#netlify) 85 | - [Now](#now) 86 | - [S3 and CloudFront](#s3-and-cloudfront) 87 | - [Surge](#surge) 88 | - [Advanced Configuration](#advanced-configuration) 89 | - [Troubleshooting](#troubleshooting) 90 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 91 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 92 | - [`npm run build` exits too early](#npm-run-build-exits-too-early) 93 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 94 | - [Moment.js locales are missing](#momentjs-locales-are-missing) 95 | - [Something Missing?](#something-missing) 96 | 97 | ## Updating to New Releases 98 | 99 | Create React App is divided into two packages: 100 | 101 | * `create-react-app` is a global command-line utility that you use to create new projects. 102 | * `react-scripts` is a development dependency in the generated projects (including this one). 103 | 104 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 105 | 106 | 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. 107 | 108 | 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. 109 | 110 | 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. 111 | 112 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 113 | 114 | ## Sending Feedback 115 | 116 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 117 | 118 | ## Folder Structure 119 | 120 | After creation, your project should look like this: 121 | 122 | ``` 123 | my-app/ 124 | README.md 125 | node_modules/ 126 | package.json 127 | public/ 128 | index.html 129 | favicon.ico 130 | src/ 131 | App.css 132 | App.js 133 | App.test.js 134 | index.css 135 | index.js 136 | logo.svg 137 | ``` 138 | 139 | For the project to build, **these files must exist with exact filenames**: 140 | 141 | * `public/index.html` is the page template; 142 | * `src/index.js` is the JavaScript entry point. 143 | 144 | You can delete or rename the other files. 145 | 146 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 147 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. 148 | 149 | Only files inside `public` can be used from `public/index.html`.<br> 150 | Read instructions below for using assets from JavaScript and HTML. 151 | 152 | You can, however, create more top-level directories.<br> 153 | They will not be included in the production build so you can use them for things like documentation. 154 | 155 | ## Available Scripts 156 | 157 | In the project directory, you can run: 158 | 159 | ### `npm start` 160 | 161 | Runs the app in the development mode.<br> 162 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 163 | 164 | The page will reload if you make edits.<br> 165 | You will also see any lint errors in the console. 166 | 167 | ### `npm test` 168 | 169 | Launches the test runner in the interactive watch mode.<br> 170 | See the section about [running tests](#running-tests) for more information. 171 | 172 | ### `npm run build` 173 | 174 | Builds the app for production to the `build` folder.<br> 175 | It correctly bundles React in production mode and optimizes the build for the best performance. 176 | 177 | The build is minified and the filenames include the hashes.<br> 178 | Your app is ready to be deployed! 179 | 180 | See the section about [deployment](#deployment) for more information. 181 | 182 | ### `npm run eject` 183 | 184 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 185 | 186 | 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. 187 | 188 | 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. 189 | 190 | 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. 191 | 192 | ## Supported Language Features and Polyfills 193 | 194 | This project supports a superset of the latest JavaScript standard.<br> 195 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 196 | 197 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 198 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 199 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). 200 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) 201 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal). 202 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. 203 | 204 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 205 | 206 | While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. 207 | 208 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: 209 | 210 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). 211 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). 212 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). 213 | 214 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. 215 | 216 | ## Syntax Highlighting in the Editor 217 | 218 | 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. 219 | 220 | ## Displaying Lint Output in the Editor 221 | 222 | >Note: this feature is available with `react-scripts@0.2.0` and higher.<br> 223 | >It also only works with npm 3 or higher. 224 | 225 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 226 | 227 | 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. 228 | 229 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: 230 | 231 | ```js 232 | { 233 | "extends": "react-app" 234 | } 235 | ``` 236 | 237 | Now your editor should report the linting warnings. 238 | 239 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes. 240 | 241 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. 242 | 243 | ## Debugging in the Editor 244 | 245 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) editor.** 246 | 247 | Visual Studio Code supports debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. 248 | 249 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. 250 | 251 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 252 | 253 | ```json 254 | { 255 | "version": "0.2.0", 256 | "configurations": [{ 257 | "name": "Chrome", 258 | "type": "chrome", 259 | "request": "launch", 260 | "url": "http://localhost:3000", 261 | "webRoot": "${workspaceRoot}/src", 262 | "userDataDir": "${workspaceRoot}/.vscode/chrome", 263 | "sourceMapPathOverrides": { 264 | "webpack:///src/*": "${webRoot}/*" 265 | } 266 | }] 267 | } 268 | ``` 269 | 270 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. 271 | 272 | ## Formatting Code Automatically 273 | 274 | Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/). 275 | 276 | To format our code whenever we make a commit in git, we need to install the following dependencies: 277 | 278 | ```sh 279 | npm install --save husky lint-staged prettier 280 | ``` 281 | 282 | Alternatively you may use `yarn`: 283 | 284 | ```sh 285 | yarn add husky lint-staged prettier 286 | ``` 287 | 288 | * `husky` makes it easy to use githooks as if they are npm scripts. 289 | * `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8). 290 | * `prettier` is the JavaScript formatter we will run before commits. 291 | 292 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. 293 | 294 | Add the following line to `scripts` section: 295 | 296 | ```diff 297 | "scripts": { 298 | + "precommit": "lint-staged", 299 | "start": "react-scripts start", 300 | "build": "react-scripts build", 301 | ``` 302 | 303 | Next we add a 'lint-staged' field to the `package.json`, for example: 304 | 305 | ```diff 306 | "dependencies": { 307 | // ... 308 | }, 309 | + "lint-staged": { 310 | + "src/**/*.{js,jsx,json,css}": [ 311 | + "prettier --single-quote --write", 312 | + "git add" 313 | + ] 314 | + }, 315 | "scripts": { 316 | ``` 317 | 318 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time. 319 | 320 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://github.com/prettier/prettier#editor-integration) on the Prettier GitHub page. 321 | 322 | ## Changing the Page `<title>` 323 | 324 | 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. 325 | 326 | 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. 327 | 328 | 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. 329 | 330 | 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). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). 331 | 332 | ## Installing a Dependency 333 | 334 | 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`: 335 | 336 | ```sh 337 | npm install --save react-router 338 | ``` 339 | 340 | Alternatively you may use `yarn`: 341 | 342 | ```sh 343 | yarn add react-router 344 | ``` 345 | 346 | This works for any library, not just `react-router`. 347 | 348 | ## Importing a Component 349 | 350 | This project setup supports ES6 modules thanks to Babel.<br> 351 | 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. 352 | 353 | For example: 354 | 355 | ### `Button.js` 356 | 357 | ```js 358 | import React, { Component } from 'react'; 359 | 360 | class Button extends Component { 361 | render() { 362 | // ... 363 | } 364 | } 365 | 366 | export default Button; // Don’t forget to use export default! 367 | ``` 368 | 369 | ### `DangerButton.js` 370 | 371 | 372 | ```js 373 | import React, { Component } from 'react'; 374 | import Button from './Button'; // Import a component from another file 375 | 376 | class DangerButton extends Component { 377 | render() { 378 | return <Button color="red" />; 379 | } 380 | } 381 | 382 | export default DangerButton; 383 | ``` 384 | 385 | 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. 386 | 387 | 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'`. 388 | 389 | 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. 390 | 391 | Learn more about ES6 modules: 392 | 393 | * [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) 394 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 395 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 396 | 397 | ## Code Splitting 398 | 399 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand. 400 | 401 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module. 402 | 403 | Here is an example: 404 | 405 | ### `moduleA.js` 406 | 407 | ```js 408 | const moduleA = 'Hello'; 409 | 410 | export { moduleA }; 411 | ``` 412 | ### `App.js` 413 | 414 | ```js 415 | import React, { Component } from 'react'; 416 | 417 | class App extends Component { 418 | handleClick = () => { 419 | import('./moduleA') 420 | .then(({ moduleA }) => { 421 | // Use moduleA 422 | }) 423 | .catch(err => { 424 | // Handle failure 425 | }); 426 | }; 427 | 428 | render() { 429 | return ( 430 | <div> 431 | <button onClick={this.handleClick}>Load</button> 432 | </div> 433 | ); 434 | } 435 | } 436 | 437 | export default App; 438 | ``` 439 | 440 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. 441 | 442 | You can also use it with `async` / `await` syntax if you prefer it. 443 | 444 | ### With React Router 445 | 446 | If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app). 447 | 448 | ## Adding a Stylesheet 449 | 450 | This project setup uses [Webpack](https://webpack.js.org/) 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**: 451 | 452 | ### `Button.css` 453 | 454 | ```css 455 | .Button { 456 | padding: 20px; 457 | } 458 | ``` 459 | 460 | ### `Button.js` 461 | 462 | ```js 463 | import React, { Component } from 'react'; 464 | import './Button.css'; // Tell Webpack that Button.js uses these styles 465 | 466 | class Button extends Component { 467 | render() { 468 | // You can use them as regular CSS styles 469 | return <div className="Button" />; 470 | } 471 | } 472 | ``` 473 | 474 | **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. 475 | 476 | 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. 477 | 478 | 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. 479 | 480 | ## Post-Processing CSS 481 | 482 | 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. 483 | 484 | For example, this: 485 | 486 | ```css 487 | .App { 488 | display: flex; 489 | flex-direction: row; 490 | align-items: center; 491 | } 492 | ``` 493 | 494 | becomes this: 495 | 496 | ```css 497 | .App { 498 | display: -webkit-box; 499 | display: -ms-flexbox; 500 | display: flex; 501 | -webkit-box-orient: horizontal; 502 | -webkit-box-direction: normal; 503 | -ms-flex-direction: row; 504 | flex-direction: row; 505 | -webkit-box-align: center; 506 | -ms-flex-align: center; 507 | align-items: center; 508 | } 509 | ``` 510 | 511 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). 512 | 513 | ## Adding a CSS Preprocessor (Sass, Less etc.) 514 | 515 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). 516 | 517 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. 518 | 519 | First, let’s install the command-line interface for Sass: 520 | 521 | ```sh 522 | npm install --save node-sass-chokidar 523 | ``` 524 | 525 | Alternatively you may use `yarn`: 526 | 527 | ```sh 528 | yarn add node-sass-chokidar 529 | ``` 530 | 531 | Then in `package.json`, add the following lines to `scripts`: 532 | 533 | ```diff 534 | "scripts": { 535 | + "build-css": "node-sass-chokidar src/ -o src/", 536 | + "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 537 | "start": "react-scripts start", 538 | "build": "react-scripts build", 539 | "test": "react-scripts test --env=jsdom", 540 | ``` 541 | 542 | >Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. 543 | 544 | Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. 545 | 546 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. 547 | 548 | To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`. 549 | 550 | ``` 551 | "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/", 552 | "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive", 553 | ``` 554 | 555 | This will allow you to do imports like 556 | 557 | ```scss 558 | @import 'styles/_colors.scss'; // assuming a styles directory under src/ 559 | @import 'nprogress/nprogress'; // importing a css file from the nprogress node module 560 | ``` 561 | 562 | At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. 563 | 564 | As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: 565 | 566 | ```sh 567 | npm install --save npm-run-all 568 | ``` 569 | 570 | Alternatively you may use `yarn`: 571 | 572 | ```sh 573 | yarn add npm-run-all 574 | ``` 575 | 576 | Then we can change `start` and `build` scripts to include the CSS preprocessor commands: 577 | 578 | ```diff 579 | "scripts": { 580 | "build-css": "node-sass-chokidar src/ -o src/", 581 | "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 582 | - "start": "react-scripts start", 583 | - "build": "react-scripts build", 584 | + "start-js": "react-scripts start", 585 | + "start": "npm-run-all -p watch-css start-js", 586 | + "build": "npm run build-css && react-scripts build", 587 | "test": "react-scripts test --env=jsdom", 588 | "eject": "react-scripts eject" 589 | } 590 | ``` 591 | 592 | Now running `npm start` and `npm run build` also builds Sass files. 593 | 594 | **Why `node-sass-chokidar`?** 595 | 596 | `node-sass` has been reported as having the following issues: 597 | 598 | - `node-sass --watch` has been reported to have *performance issues* in certain conditions when used in a virtual machine or with docker. 599 | 600 | - Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939) 601 | 602 | - `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891) 603 | 604 | `node-sass-chokidar` is used here as it addresses these issues. 605 | 606 | ## Adding Images, Fonts, and Files 607 | 608 | With Webpack, using static assets like images and fonts works similarly to CSS. 609 | 610 | You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. 611 | 612 | To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebookincubator/create-react-app/issues/1153). 613 | 614 | Here is an example: 615 | 616 | ```js 617 | import React from 'react'; 618 | import logo from './logo.png'; // Tell Webpack this JS file uses this image 619 | 620 | console.log(logo); // /logo.84287d09.png 621 | 622 | function Header() { 623 | // Import result is the URL of your image 624 | return <img src={logo} alt="Logo" />; 625 | } 626 | 627 | export default Header; 628 | ``` 629 | 630 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 631 | 632 | This works in CSS too: 633 | 634 | ```css 635 | .Logo { 636 | background-image: url(./logo.png); 637 | } 638 | ``` 639 | 640 | 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. 641 | 642 | Please be advised that this is also a custom feature of Webpack. 643 | 644 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 645 | An alternative way of handling static assets is described in the next section. 646 | 647 | ## Using the `public` Folder 648 | 649 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 650 | 651 | ### Changing the HTML 652 | 653 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 654 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 655 | 656 | ### Adding Assets Outside of the Module System 657 | 658 | You can also add other assets to the `public` folder. 659 | 660 | Note that we normally encourage you to `import` assets in JavaScript files instead. 661 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). 662 | This mechanism provides a number of benefits: 663 | 664 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 665 | * Missing files cause compilation errors instead of 404 errors for your users. 666 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 667 | 668 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 669 | 670 | 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`. 671 | 672 | Inside `index.html`, you can use it like this: 673 | 674 | ```html 675 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 676 | ``` 677 | 678 | 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. 679 | 680 | 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. 681 | 682 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 683 | 684 | ```js 685 | render() { 686 | // Note: this is an escape hatch and should be used sparingly! 687 | // Normally we recommend using `import` for getting asset URLs 688 | // as described in “Adding Images and Fonts” above this section. 689 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 690 | } 691 | ``` 692 | 693 | Keep in mind the downsides of this approach: 694 | 695 | * None of the files in `public` folder get post-processed or minified. 696 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 697 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 698 | 699 | ### When to Use the `public` Folder 700 | 701 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. 702 | The `public` folder is useful as a workaround for a number of less common cases: 703 | 704 | * 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). 705 | * You have thousands of images and need to dynamically reference their paths. 706 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 707 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 708 | 709 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 710 | 711 | ## Using Global Variables 712 | 713 | 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. 714 | 715 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 716 | 717 | ```js 718 | const $ = window.$; 719 | ``` 720 | 721 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 722 | 723 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 724 | 725 | ## Adding Bootstrap 726 | 727 | 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: 728 | 729 | Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 730 | 731 | ```sh 732 | npm install --save react-bootstrap bootstrap@3 733 | ``` 734 | 735 | Alternatively you may use `yarn`: 736 | 737 | ```sh 738 | yarn add react-bootstrap bootstrap@3 739 | ``` 740 | 741 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: 742 | 743 | ```js 744 | import 'bootstrap/dist/css/bootstrap.css'; 745 | import 'bootstrap/dist/css/bootstrap-theme.css'; 746 | // Put any other imports below so that CSS from your 747 | // components takes precedence over default styles. 748 | ``` 749 | 750 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 751 | 752 | ```js 753 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 754 | ``` 755 | 756 | 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. 757 | 758 | ### Using a Custom Theme 759 | 760 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 761 | We suggest the following approach: 762 | 763 | * Create a new package that depends on the package you wish to customize, e.g. Bootstrap. 764 | * Add the necessary build steps to tweak the theme, and publish your package on npm. 765 | * Install your own theme npm package as a dependency of your app. 766 | 767 | Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. 768 | 769 | ## Adding Flow 770 | 771 | 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. 772 | 773 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 774 | 775 | To add Flow to a Create React App project, follow these steps: 776 | 777 | 1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). 778 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 779 | 3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. 780 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 781 | 782 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 783 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 784 | In the future we plan to integrate it into Create React App even more closely. 785 | 786 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 787 | 788 | ## Adding Custom Environment Variables 789 | 790 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 791 | 792 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 793 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 794 | `REACT_APP_`. 795 | 796 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 797 | 798 | >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). Changing any environment variables will require you to restart the development server if it is running. 799 | 800 | These environment variables will be defined for you on `process.env`. For example, having an environment 801 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 802 | 803 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 804 | 805 | These environment variables can be useful for displaying information conditionally based on where the project is 806 | deployed or consuming sensitive data that lives outside of version control. 807 | 808 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 809 | in the environment inside a `<form>`: 810 | 811 | ```jsx 812 | render() { 813 | return ( 814 | <div> 815 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 816 | <form> 817 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 818 | </form> 819 | </div> 820 | ); 821 | } 822 | ``` 823 | 824 | 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. 825 | 826 | 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`: 827 | 828 | ```html 829 | <div> 830 | <small>You are running this application in <b>development</b> mode.</small> 831 | <form> 832 | <input type="hidden" value="abcdef" /> 833 | </form> 834 | </div> 835 | ``` 836 | 837 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 838 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 839 | a `.env` file. Both of these ways are described in the next few sections. 840 | 841 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 842 | 843 | ```js 844 | if (process.env.NODE_ENV !== 'production') { 845 | analytics.disable(); 846 | } 847 | ``` 848 | 849 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 850 | 851 | ### Referencing Environment Variables in the HTML 852 | 853 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 854 | 855 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 856 | 857 | ```html 858 | <title>%REACT_APP_WEBSITE_NAME% 859 | ``` 860 | 861 | Note that the caveats from the above section apply: 862 | 863 | * Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 864 | * The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 865 | 866 | ### Adding Temporary Environment Variables In Your Shell 867 | 868 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 869 | life of the shell session. 870 | 871 | #### Windows (cmd.exe) 872 | 873 | ```cmd 874 | set REACT_APP_SECRET_CODE=abcdef&&npm start 875 | ``` 876 | 877 | (Note: the lack of whitespace is intentional.) 878 | 879 | #### Linux, macOS (Bash) 880 | 881 | ```bash 882 | REACT_APP_SECRET_CODE=abcdef npm start 883 | ``` 884 | 885 | ### Adding Development Environment Variables In `.env` 886 | 887 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 888 | 889 | To define permanent environment variables, create a file called `.env` in the root of your project: 890 | 891 | ``` 892 | REACT_APP_SECRET_CODE=abcdef 893 | ``` 894 | 895 | `.env` files **should be** checked into source control (with the exclusion of `.env*.local`). 896 | 897 | #### What other `.env` files are can be used? 898 | 899 | >Note: this feature is **available with `react-scripts@1.0.0` and higher**. 900 | 901 | * `.env`: Default. 902 | * `.env.local`: Local overrides. **This file is loaded for all environments except test.** 903 | * `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. 904 | * `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. 905 | 906 | Files on the left have more priority than files on the right: 907 | 908 | * `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` 909 | * `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` 910 | * `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) 911 | 912 | These variables will act as the defaults if the machine does not explicitly set them.
913 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 914 | 915 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 916 | 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). 917 | 918 | ## Can I Use Decorators? 919 | 920 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
921 | Create React App doesn’t support decorator syntax at the moment because: 922 | 923 | * It is an experimental proposal and is subject to change. 924 | * The current specification version is not officially supported by Babel. 925 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 926 | 927 | However in many cases you can rewrite decorator-based code without decorators just as fine.
928 | Please refer to these two threads for reference: 929 | 930 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 931 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 932 | 933 | Create React App will add decorator support when the specification advances to a stable stage. 934 | 935 | ## Integrating with an API Backend 936 | 937 | These tutorials will help you to integrate your app with an API backend running on another port, 938 | using `fetch()` to access it. 939 | 940 | ### Node 941 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 942 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 943 | 944 | ### Ruby on Rails 945 | 946 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 947 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 948 | 949 | ## Proxying API Requests in Development 950 | 951 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 952 | 953 | People often serve the front-end React app from the same host and port as their backend implementation.
954 | For example, a production setup might look like this after the app is deployed: 955 | 956 | ``` 957 | / - static server returns index.html with React app 958 | /todos - static server returns index.html with React app 959 | /api/todos - server handles any /api/* requests using the backend implementation 960 | ``` 961 | 962 | 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. 963 | 964 | 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: 965 | 966 | ```js 967 | "proxy": "http://localhost:4000", 968 | ``` 969 | 970 | 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. 971 | 972 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 973 | 974 | ``` 975 | 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. 976 | ``` 977 | 978 | 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`. 979 | 980 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
981 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 982 | 983 | * [Configure the proxy yourself](#configuring-the-proxy-manually) 984 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 985 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 986 | 987 | ### "Invalid Host Header" Errors After Configuring Proxy 988 | 989 | When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). 990 | 991 | This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebookincubator/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: 992 | 993 | >Invalid Host header 994 | 995 | To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: 996 | 997 | ``` 998 | HOST=mypublicdevhost.com 999 | ``` 1000 | 1001 | If you restart the development server now and load the app from the specified host, it should work. 1002 | 1003 | If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** 1004 | 1005 | ``` 1006 | # NOTE: THIS IS DANGEROUS! 1007 | # It exposes your machine to attacks from the websites you visit. 1008 | DANGEROUSLY_DISABLE_HOST_CHECK=true 1009 | ``` 1010 | 1011 | We don’t recommend this approach. 1012 | 1013 | ### Configuring the Proxy Manually 1014 | 1015 | >Note: this feature is available with `react-scripts@1.0.0` and higher. 1016 | 1017 | If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).
1018 | You may also specify any configuration value [`http-proxy-middleware`](https://github.com/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://github.com/nodejitsu/node-http-proxy#options) supports. 1019 | ```js 1020 | { 1021 | // ... 1022 | "proxy": { 1023 | "/api": { 1024 | "target": "", 1025 | "ws": true 1026 | // ... 1027 | } 1028 | } 1029 | // ... 1030 | } 1031 | ``` 1032 | 1033 | All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. 1034 | 1035 | If you need to specify multiple proxies, you may do so by specifying additional entries. 1036 | You may also narrow down matches using `*` and/or `**`, to match the path exactly or any subpath. 1037 | ```js 1038 | { 1039 | // ... 1040 | "proxy": { 1041 | // Matches any request starting with /api 1042 | "/api": { 1043 | "target": "", 1044 | "ws": true 1045 | // ... 1046 | }, 1047 | // Matches any request starting with /foo 1048 | "/foo": { 1049 | "target": "", 1050 | "ssl": true, 1051 | "pathRewrite": { 1052 | "^/foo": "/foo/beta" 1053 | } 1054 | // ... 1055 | }, 1056 | // Matches /bar/abc.html but not /bar/sub/def.html 1057 | "/bar/*.html": { 1058 | "target": "", 1059 | // ... 1060 | }, 1061 | // Matches /baz/abc.html and /baz/sub/def.html 1062 | "/baz/**/*.html": { 1063 | "target": "" 1064 | // ... 1065 | } 1066 | } 1067 | // ... 1068 | } 1069 | ``` 1070 | 1071 | ### Configuring a WebSocket Proxy 1072 | 1073 | When setting up a WebSocket proxy, there are a some extra considerations to be aware of. 1074 | 1075 | If you’re using a WebSocket engine like [Socket.io](https://socket.io/), you must have a Socket.io server running that you can use as the proxy target. Socket.io will not work with a standard WebSocket server. Specifically, don't expect Socket.io to work with [the websocket.org echo test](http://websocket.org/echo.html). 1076 | 1077 | There’s some good documentation available for [setting up a Socket.io server](https://socket.io/docs/). 1078 | 1079 | Standard WebSockets **will** work with a standard WebSocket server as well as the websocket.org echo test. You can use libraries like [ws](https://github.com/websockets/ws) for the server, with [native WebSockets in the browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). 1080 | 1081 | Either way, you can proxy WebSocket requests manually in `package.json`: 1082 | 1083 | ```js 1084 | { 1085 | // ... 1086 | "proxy": { 1087 | "/socket": { 1088 | // Your compatible WebSocket server 1089 | "target": "ws://", 1090 | // Tell http-proxy-middleware that this is a WebSocket proxy. 1091 | // Also allows you to proxy WebSocket requests without an additional HTTP request 1092 | // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade 1093 | "ws": true 1094 | // ... 1095 | } 1096 | } 1097 | // ... 1098 | } 1099 | ``` 1100 | 1101 | ## Using HTTPS in Development 1102 | 1103 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 1104 | 1105 | 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. 1106 | 1107 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 1108 | 1109 | #### Windows (cmd.exe) 1110 | 1111 | ```cmd 1112 | set HTTPS=true&&npm start 1113 | ``` 1114 | 1115 | (Note: the lack of whitespace is intentional.) 1116 | 1117 | #### Linux, macOS (Bash) 1118 | 1119 | ```bash 1120 | HTTPS=true npm start 1121 | ``` 1122 | 1123 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 1124 | 1125 | ## Generating Dynamic `` Tags on the Server 1126 | 1127 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 1128 | 1129 | ```html 1130 | 1131 | 1132 | 1133 | 1134 | 1135 | ``` 1136 | 1137 | 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! 1138 | 1139 | 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. 1140 | 1141 | ## Pre-Rendering into Static HTML Files 1142 | 1143 | If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. 1144 | 1145 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 1146 | 1147 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 1148 | 1149 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 1150 | 1151 | ## Injecting Data from the Server into the Page 1152 | 1153 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 1154 | 1155 | ```js 1156 | 1157 | 1158 | 1159 | 1162 | ``` 1163 | 1164 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** 1165 | 1166 | ## Running Tests 1167 | 1168 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
1169 | >[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) 1170 | 1171 | 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. 1172 | 1173 | 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. 1174 | 1175 | 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. 1176 | 1177 | 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. 1178 | 1179 | ### Filename Conventions 1180 | 1181 | Jest will look for test files with any of the following popular naming conventions: 1182 | 1183 | * Files with `.js` suffix in `__tests__` folders. 1184 | * Files with `.test.js` suffix. 1185 | * Files with `.spec.js` suffix. 1186 | 1187 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 1188 | 1189 | 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. 1190 | 1191 | ### Command Line Interface 1192 | 1193 | 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. 1194 | 1195 | 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: 1196 | 1197 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 1198 | 1199 | ### Version Control Integration 1200 | 1201 | 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 run 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. 1202 | 1203 | 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. 1204 | 1205 | 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. 1206 | 1207 | ### Writing Tests 1208 | 1209 | 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. 1210 | 1211 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 1212 | 1213 | ```js 1214 | import sum from './sum'; 1215 | 1216 | it('sums numbers', () => { 1217 | expect(sum(1, 2)).toEqual(3); 1218 | expect(sum(2, 2)).toEqual(4); 1219 | }); 1220 | ``` 1221 | 1222 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1223 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. 1224 | 1225 | ### Testing Components 1226 | 1227 | 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. 1228 | 1229 | 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: 1230 | 1231 | ```js 1232 | import React from 'react'; 1233 | import ReactDOM from 'react-dom'; 1234 | import App from './App'; 1235 | 1236 | it('renders without crashing', () => { 1237 | const div = document.createElement('div'); 1238 | ReactDOM.render(, div); 1239 | }); 1240 | ``` 1241 | 1242 | 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`. 1243 | 1244 | 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. 1245 | 1246 | 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/). To install it, run: 1247 | 1248 | ```sh 1249 | npm install --save enzyme react-test-renderer 1250 | ``` 1251 | 1252 | Alternatively you may use `yarn`: 1253 | 1254 | ```sh 1255 | yarn add enzyme react-test-renderer 1256 | ``` 1257 | 1258 | You can write a smoke test with it too: 1259 | 1260 | ```js 1261 | import React from 'react'; 1262 | import { shallow } from 'enzyme'; 1263 | import App from './App'; 1264 | 1265 | it('renders without crashing', () => { 1266 | shallow(); 1267 | }); 1268 | ``` 1269 | 1270 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a ` 46 | 47 | { 48 | this.state.notes.map((note, index) => { 49 | return ( 50 | 51 | ) 52 | }) 53 | } 54 |
55 | 56 | 57 | ) 58 | } 59 | } 60 | 61 | export default App; -------------------------------------------------------------------------------- /notetoself/src/components/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { mount } from 'enzyme'; 3 | import App from './App'; 4 | 5 | describe('App', () => { 6 | let app = mount(); 7 | 8 | it('renders the App title', () => { 9 | // console.log(app.debug()); 10 | expect(app.find('h2').text()).toEqual('Note to Self'); 11 | }); 12 | 13 | it('renders the clear button', () => { 14 | expect(app.find('.btn').at(1).text()).toEqual('Clear Notes'); 15 | }); 16 | 17 | describe('when rendering the form', () => { 18 | it('creates a Form component', () => { 19 | expect(app.find('Form').exists()).toBe(true); 20 | }); 21 | 22 | it('renders a FormControl component', () => { 23 | expect(app.find('FormControl').exists()).toBe(true); 24 | }); 25 | 26 | it('renders a submit button', () => { 27 | expect(app.find('.btn').at(0).text()).toEqual('Submit'); 28 | }); 29 | }); 30 | 31 | describe('when creating a note', () => { 32 | let testNote = 'test note'; 33 | 34 | beforeEach(() => { 35 | app.find('FormControl').simulate('change', { 36 | target: { value: testNote } 37 | }); 38 | }); 39 | 40 | it('updates the text in state', () => { 41 | expect(app.state().text).toEqual(testNote); 42 | }); 43 | 44 | describe('and submitting the new note', () => { 45 | beforeEach(() => { 46 | app.find('.btn').at(0).simulate('click'); 47 | }); 48 | 49 | afterEach(() => { 50 | app.find('.btn').at(1).simulate('click'); 51 | }); 52 | 53 | it('adds the new note to the state', () => { 54 | // console.log(app.state()); 55 | expect(app.state().notes[0].text).toEqual(testNote); 56 | }); 57 | 58 | describe('and remounting the component', () => { 59 | let app2; 60 | 61 | beforeEach(() => { 62 | app2 = mount(); 63 | }); 64 | 65 | it('reads the stored note cookies', () => { 66 | expect(app2.state().notes).toEqual([{ text: testNote }]); 67 | }); 68 | }); 69 | 70 | describe('and clicking the clear button', () => { 71 | beforeEach(() => { 72 | app.find('.btn').at(1).simulate('click'); 73 | }); 74 | 75 | it('clears the notes in state', () => { 76 | // console.log(app.state()); 77 | expect(app.state().notes).toEqual([]); 78 | }); 79 | }); 80 | }); 81 | }); 82 | }); -------------------------------------------------------------------------------- /notetoself/src/components/Note.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | 3 | class Note extends Component { 4 | render() { 5 | return ( 6 |
7 |

{this.props.note.text}

8 |
9 | ) 10 | } 11 | } 12 | 13 | export default Note; -------------------------------------------------------------------------------- /notetoself/src/components/Note.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { mount } from 'enzyme'; 3 | import Note from './Note'; 4 | 5 | const props = { note: { text: 'test_note' } }; 6 | 7 | describe('Note', () => { 8 | let note = mount(); 9 | 10 | it('renders the note text', () => { 11 | expect(note.find('p').text()).toEqual(props.note.text); 12 | }); 13 | }); -------------------------------------------------------------------------------- /notetoself/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | text-align: center; 3 | padding: 5%; 4 | } 5 | 6 | .note { 7 | border: 1px solid lightgray; 8 | border-radius: 5px; 9 | font-style: italic; 10 | text-align: left; 11 | padding: 8px; 12 | margin: 30px; 13 | } -------------------------------------------------------------------------------- /notetoself/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './components/App'; 4 | import './index.css'; 5 | 6 | ReactDOM.render(, document.getElementById('root')); --------------------------------------------------------------------------------