Edited and formatted by ericwm76
Eric's gist https://gist.github.com/ericwm76/e1204fc03f14af4429add8225ff55f71
Creating a React App
- In the terminal run
npx create-react-app NAMEOFYOURAPP
- Cd into the new directory:
cd NAMEOFYOURAPP
- Run
npm install
. - You can run
npm start
to see if the app was set up correctly.
Setting Up Testing
- Install enzyme:
npm i enzyme -D
- Install enzyme-adapter-react-16:
npm install enzyme-adapter-react-16 -D
- Inside of /src create setupTests.js:
touch src/setupTests.js
- Put the following 3 lines of code in setupTests.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
- For snapshot testing, install enzyme-to-json
npm install enzyme-to-json -D
- In package.json, add the following lines of code:
"jest": {
"snapshotSerializers": [
"enzyme-to-json/serializer"
]
}
Don't forget the comma!
- Add an extra line in App.js (just so there's a change in the file) and save. Then run
npm test
to check that the files are connected correctly. - Include the following lines as headers for all test files:
import React from 'react';
import { shallow } from 'enzyme';
import ClassName from './ClassName';
npm install --save react-router-dom
import { BrowserRouter as Router, Switch, Route} from 'react-router-dom'
you can rename longer import by the example of 'BrowserRouter' above.
Rather than placing components directly into App, they are established as routes.
The entire return JSX for App will be wrapped in <Router></Router> tags
function App() {
return (
<Router>
<div className="App">
<Nav />
<Switch>
<Route path="/" component={Home}/>
<Route path="/about" component={About} />
<Route path="/shop" component={Shop} />
</Switch>
</div>
</Router>
);
}
Decide which component is on each route by adding component={yourComponentName}
Also, establish which path it is set at from the root URL by path="/yourComponent"
The above code has an issue to check to see if path has a / for the first item. This causes issues with Routes becoming combined due to the path="/"
Enclose the Routes in <Switch></Switch>
Now the routes wont be combined but it will stop at the first component that fulfills any part of its search criteria.
By adding exact
into the component properties, it will only go to Routes that exactly match the URL directory name.
<Route path="/" exact component={Home}/>
To be able to click between routes rather than having to enter the path into the browser, go to your navigation component and import { Link } from 'react-router-dom'
Then, in the Nav component, we wrap the li's where the links would go in tags.
To direct these Links to the proper page, we would give them the property to="/myComponent"
Ex:
function Nav() {
return (
<nav>
<h3>Logo</h3>
<ul className="nav-links">
<Link to='/about'>
<li>About</li>
</Link>
<Link to='/shop'>
<li>Shop</li>
</Link>
</ul>
</nav>
);
}
npm install prop-types -S