Skip to content

Commit

Permalink
Initial commit of code example files
Browse files Browse the repository at this point in the history
  • Loading branch information
jimmyzhen committed Dec 11, 2024
0 parents commit 18d3546
Show file tree
Hide file tree
Showing 9 changed files with 10,338 additions and 0 deletions.
70 changes: 70 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# next.js build output
.next

# Mac autogenerated folder information (file color/position/etc)
.DS_Store

# Snapshots
src/__snapshots__/*

# VS Code user settings
.vscode/
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
**Instructions to reproduce the eror**
---

#### Preparation

Set `node` environment to `20.11.0`, or use `nvm` to run `nvm use 20.11.0`

#### Steps

1. Clone the repo
2. Run `yarn install`
3. Run `yarn test`

#### Expected behavior

All tests should pass.

#### Actual behavior

```
ReferenceError: TextEncoder is not defined
> 1 | import { configure } from 'enzyme';
| ^
2 | import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
3 |
4 | const crypto = require('crypto');
at Object.<anonymous> (node_modules/undici/lib/web/fetch/data-url.js:5:17)
at Object.<anonymous> (node_modules/undici/lib/web/fetch/util.js:7:97)
at Object.<anonymous> (node_modules/undici/lib/web/fetch/headers.js:11:5)
at Object.<anonymous> (node_modules/undici/lib/web/fetch/response.js:3:90)
at Object.<anonymous> (node_modules/undici/lib/web/fetch/index.js:11:5)
at Object.<anonymous> (node_modules/undici/index.js:106:19)
at Object.<anonymous> (node_modules/cheerio/src/index.ts:24:1)
at Object.<anonymous> (node_modules/enzyme/src/Utils.js:9:1)
at Object.<anonymous> (node_modules/enzyme/src/ReactWrapper.js:4:1)
at Object.<anonymous> (node_modules/enzyme/src/index.js:1:1)
at Object.<anonymous> (src/setupTests.js:1:1)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:404:19)
```
29 changes: 29 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "code-example",
"version": "0.1.0",
"private": true,
"dependencies": {
"crypto": "^1.0.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-router-dom": "^5.1.2",
"react-scripts": "5.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"@wojtekmaj/enzyme-adapter-react-17": "0.8.0",
"enzyme": "3.11.0"
}
}
19 changes: 19 additions & 0 deletions src/App/__test__/app.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from 'react';
import { shallow, mount } from 'enzyme';
import App from '../app';

describe('<App />', () => {
let component;

beforeEach(() => {
component = shallow(<App />);
});

test('It should mount', () => {
expect(component.length).toBe(1);
});

test('It should contain 2 routes', () => {
expect(component.find('Route').length).toBe(2);
});
});
45 changes: 45 additions & 0 deletions src/App/app.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React from 'react';
import { Router, Route, Switch, Link } from 'react-router-dom';

function App() {
return (
<Router>
<div className="App container">
<div className="row justify-content-center">
<Switch>
<Route
path="/"
exact
component={LandingPage}
/>
<Route
path="/details"
component={DetailsPage}
/>

</Switch>
</div>
</div>
</Router>
);
}

export default App;

function LandingPage() {
return (
<div>
<h1>Landing Page</h1>
<Link to="/details">Go to Details Page</Link>
</div>
);
}

function DetailsPage() {
return (
<div>
<h1>Details Page</h1>
<Link to="/">Back</Link>
</div>
);
}
11 changes: 11 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from 'react';
import { render } from 'react-dom';
import App from './App/app';
import * as serviceWorker from './serviceWorker';

render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
131 changes: 131 additions & 0 deletions src/serviceWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// This optional code is used to register a service worker.
// register() is not called by default.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.

// To learn more about the benefits of this model and instructions on how to
// opt-in, read http://bit.ly/CRA-PWA.

const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);

export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}

window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);

// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit http://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}

function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See http://bit.ly/CRA-PWA.'
);

// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');

// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}

function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}

export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
20 changes: 20 additions & 0 deletions src/setupTests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { configure } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';

const crypto = require('crypto');

configure({ adapter: new Adapter() });

// fix for 'crypto.getRandomValues() not supported' error
Object.defineProperty(globalThis, 'crypto', {
value: {
getRandomValues: (arr) => crypto.randomBytes(arr.length),
},
});

// fix for 'unstable_flushDiscreteUpdates: Cannot flush updates when React is already rendering' error
// when <video> is used in a component
// (https://github.com/testing-library/react-testing-library/issues/470#issuecomment-761821103)
Object.defineProperty(HTMLMediaElement.prototype, 'muted', {
set: () => {},
});
Loading

0 comments on commit 18d3546

Please sign in to comment.