make-tests-work #7

Open
aCheeseInTheDark wants to merge 16 commits from make-tests-work into master
26 changed files with 3145 additions and 343 deletions

View File

@ -0,0 +1,10 @@
name: Test
run-name: Test?
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm install && npm run test

6
.gitignore vendored
View File

@ -1,5 +1,9 @@
.env
data/
node_modules/
build/
public/
build/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/

19
.prettierrc Normal file
View File

@ -0,0 +1,19 @@
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": false,
"overrides": [
{
"files": [
"*.test.ts",
"*.test.js",
"*.spec.ts",
"*.spec.js"
],
"options": {
"maxLineLength": 9999999
}
}
]
}

31
.swcrc Normal file
View File

@ -0,0 +1,31 @@
{
"jsc": {
"target": "es2022",
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": false,
"dynamicImport": false
},
"transform": {
"react": {
"pragma": "React.createElement",
"pragmaFrag": "React.Fragment",
"throwIfNamespace": true,
"development": false,
"useBuiltins": false,
"runtime": "automatic"
},
"hidden": {
"jest": true
}
}
},
"module": {
"type": "commonjs",
"strict": false,
"strictMode": true,
"lazy": false,
"noInterop": false
}
}

View File

@ -11,6 +11,7 @@ import { createReadableStreamFromReadable } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { isbot } from "isbot";
import { renderToPipeableStream } from "react-dom/server";
import React from "react";
const ABORT_DELAY = 5_000;

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 299 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 947 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

BIN
app/images/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1 @@
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}

45
app/root.test.tsx Normal file
View File

@ -0,0 +1,45 @@
import { act, render, screen, waitFor } from '@testing-library/react'
import MatchMediaMock from 'jest-matchmedia-mock';
import { createRemixStub, RemixStubProps } from "@remix-run/testing"
import App from './root'
import React from 'react'
let RemixStub: (props: RemixStubProps) => React.JSX.Element
describe("root", () => {
beforeEach(() => {
RemixStub = createRemixStub([
{
path: "/",
meta: () => ([]),
links: () => ([]),
loader: () => ({ isSupported: true}),
Component: App
}
])
})
let matchMedia: MatchMediaMock
beforeAll(() => {
matchMedia = new MatchMediaMock();
})
afterEach(() => {
matchMedia.clear();
})
describe("when user is on iOS", () => {
describe("version 16.4 or higher", () => {
describe("and tack up now is not already installed on their device", () => {
test("they are instructed to install tack up now", async () => {
render(<RemixStub/>)
await waitFor(() => screen.findByText<HTMLElement>(/Install/), { timeout: 2000 })
expect(true).toBe(true)
})
})
})
})
})

View File

@ -1,29 +1,71 @@
import { json, LoaderFunctionArgs } from "@remix-run/node"
import {
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration,
} from "@remix-run/react";
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration,
useLoaderData,
} from "@remix-run/react"
import React, { useEffect } from "react"
import UAParser from "ua-parser-js"
import versionAtLeast from "semver/functions/gte"
import coerceSemver from "semver/functions/coerce"
// import { LandingMessage } from "./root.client"
export function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
);
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1"
/>
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
)
}
export const loader = async ({ request }: LoaderFunctionArgs) => {
const userAgent = request.headers.get("user-agent")
const os = new UAParser(userAgent ?? "").getOS()
const isSupported =
os.name !== "iOS" ||
versionAtLeast(coerceSemver(os.version) ?? "0.0.0", "16.4.0")
return json({ isSupported })
}
export default function App() {
return <Outlet />;
const { isSupported } = useLoaderData<typeof loader>()
return <><Outlet/><LandingMessage isSupported={isSupported}/></>
}
function LandingMessage({ isSupported }: { isSupported: boolean }) {
useEffect(() => {
console.log("WTF")
}, [])
if (typeof window === "undefined") return <div>WHY</div>
const isRunningPWA = "standalone" in navigator && navigator.standalone || matchMedia("(dislay-mode: standalone)").matches
const message = isRunningPWA
? "Enable notifications"
: isSupported
? "Install Tack Up Now!"
: "Sorry, your device doesn't support Tack Up Now! :("
return <div>{message}</div>
}

View File

@ -1,4 +1,5 @@
import type { MetaFunction } from "@remix-run/node";
import React from "react";
export const meta: MetaFunction = () => {
return [
@ -12,7 +13,6 @@ export default function Index() {
<div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.8" }}>
<h1>WHOAH! A WEBSITE</h1>
<div>Hey check it out!</div>
</div>
);
}

View File

@ -6,7 +6,7 @@ services:
database:
image: postgres
ports:
- "0.0.0.0:5433:5432"
- "5433:5432"
environment:
POSTGRES_PASSWORD: $POSTGRES_PASSWORD
POSTGRES_USER: postgres

77
e2e/install.spec.ts Normal file
View File

@ -0,0 +1,77 @@
import { test, expect } from "@playwright/test"
const { describe, beforeEach, skip, use } = test
function webkitOnly() {
beforeEach(async ({ browserName }) => {
if (browserName !== "webkit") skip()
})
}
describe("when user is on iOS", () => {
webkitOnly()
describe("version 16.4 or higher", () => {
use({
userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Mobile/15E148 Safari/604.1",
})
test("and tack up now is not running as a PWA, they are instructed to install tack up now", async ({ page }) => {
await page.goto("/")
const installText = await page.getByText(/Install Tack Up Now!/)
await expect(installText).toBeAttached()
})
describe("and tack up now is running as a PWA", () => {
beforeEach(async ({ page }) => {
await page.addInitScript(() => (window.navigator as any)["standalone"] = true)
})
test("and notifications aren't enabled, they are asked to enable notifications", async ({ page, browser }) => {
await page.goto("/")
const notificationText = await page.getByText(/Enable notifications/)
await expect(notificationText).toBeAttached()
})
// describe("and notifications are enabled", () => {
// beforeEach(async ({ page }) => {
// await page.addInitScript(() => (window.persmis))
// })
// test("they aren't asked to enable notifications", async ({ browser }) => {
// const context = await browser.newContext({
// permissions: ['notification'],
// });
// const page = await context.newPage()
// await page.goto("/")
// const notificationText = await page.getByText(/Enable notifications/)
// await expect(notificationText).not.toBeAttached()
// })
// })
})
})
describe("version 16.3 and under", () => {
use({
userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 16_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Mobile/15E148 Safari/604.1",
})
test("version 16.3 and under they are informed that their iOS version isn't supported", async ({ page }) => {
await page.goto("/")
const sorryText = await page.getByText("Sorry, your device doesn't support Tack Up Now! :(")
await expect(sorryText).toBeVisible()
})
})
})

31
jest.config.ts Normal file
View File

@ -0,0 +1,31 @@
const ignorePatterns = [
"\\/build\\/",
"\\/coverage\\/",
"\\/\\.vscode\\/",
"\\/\\.tmp\\/",
"\\/\\.cache\\/",
"data",
"e2e"
];
module.exports = {
moduleNameMapper: {
"^@web3-storage/multipart-parser$": require.resolve(
"@web3-storage/multipart-parser"
),
},
modulePathIgnorePatterns: ignorePatterns,
transform: {
"\\.[jt]sx?$": require.resolve("./transform"),
},
transformIgnorePatterns: [],
watchPathIgnorePatterns: [...ignorePatterns, "\\/node_modules\\/"],
watchPlugins: [
require.resolve("jest-watch-typeahead/filename"),
require.resolve("jest-watch-typeahead/testname"),
],
displayName: "testing",
setupFiles: [],
testEnvironment: "jsdom",
setupFilesAfterEnv: ["./setupTests.ts", "@testing-library/jest-dom"],
};

2974
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -9,7 +9,8 @@
"lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .",
"start": "remix-serve ./build/server/index.js",
"typecheck": "tsc",
"test": "jest --watch"
"watch": "jest --watch --config=jest.config.ts",
"test": "jest --config=jest.config.ts"
},
"dependencies": {
"@remix-run/express": "^2.9.1",
@ -20,20 +21,37 @@
"express": "^4.19.2",
"isbot": "^4.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"react-dom": "^18.2.0",
"remix-utils": "^7.6.0",
"semver": "^7.6.3",
"ua-parser-js": "^1.0.39"
},
"devDependencies": {
"@babel/core": "^7.24.5",
"@babel/plugin-proposal-export-namespace-from": "^7.18.9",
"@babel/plugin-proposal-optional-chaining": "^7.21.0",
"@babel/preset-env": "^7.24.5",
"@babel/preset-react": "^7.24.1",
"@babel/preset-typescript": "^7.24.1",
"@playwright/test": "^1.44.1",
"@remix-run/dev": "^2.9.0",
"@remix-run/testing": "^2.9.1",
"@swc/core": "^1.5.7",
"@swc/jest": "^0.2.36",
"@testing-library/jest-dom": "^6.4.5",
"@testing-library/react": "^15.0.4",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.12",
"@types/node": "^20.14.5",
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"@types/semver": "^7.5.8",
"@types/supertest": "^6.0.2",
"@types/ua-parser-js": "^0.7.39",
"@typescript-eslint/eslint-plugin": "^6.7.4",
"@typescript-eslint/parser": "^6.7.4",
"chai": "^4.4.1",
"chai-as-promised": "^7.1.1",
"babel-jest": "^29.7.0",
"babel-plugin-transform-remove-console": "^6.9.4",
"eslint": "^8.38.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.28.1",
@ -41,8 +59,10 @@
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"jest": "^29.7.0",
"sinon": "^17.0.1",
"sinon-chai": "^3.7.0",
"jest-environment-jsdom": "^29.7.0",
"jest-matchmedia-mock": "^1.1.0",
"jest-watch-typeahead": "^2.2.2",
"prettier": "^3.3.3",
"supertest": "^7.0.0",
"ts-node": "^10.9.2",
"typescript": "^5.1.6",

66
playwright.config.ts Normal file
View File

@ -0,0 +1,66 @@
import { defineConfig, devices } from '@playwright/test';
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: './e2e',
testMatch: "*.spec.ts",
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://127.0.0.1:5173',
ignoreHTTPSErrors: true,
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},
/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
/* Test against mobile viewports. */
{
name: 'Mobile Chrome',
use: { ...devices['Pixel 5'] },
},
{
name: 'Mobile Safari',
use: { ...devices['iPhone 12'] },
},
],
/* Run your local dev server before starting the tests */
webServer: {
command: 'npm run dev',
url: 'http://127.0.0.1:5173',
reuseExistingServer: !process.env.CI,
},
});

View File

16
setupTests.ts Normal file
View File

@ -0,0 +1,16 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import React from 'react'
import '@testing-library/jest-dom'
const JSDOMFormData = global.FormData;
global.React = React
global.TextDecoder = require("util").TextDecoder;
global.TextEncoder = require("util").TextEncoder;
global.ReadableStream = require("stream/web").ReadableStream;
global.WritableStream = require("stream/web").WritableStream;
require("@remix-run/node").installGlobals({ nativeFetch: true });
global.FormData = JSDOMFormData;

27
thebabel.config.cjs Normal file
View File

@ -0,0 +1,27 @@
module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "18",
},
},
],
"@babel/preset-react",
"@babel/preset-typescript",
],
plugins: [
"@babel/plugin-proposal-export-namespace-from",
"@babel/plugin-proposal-optional-chaining",
// Strip console.debug calls unless REMIX_DEBUG=true
...(process.env.REMIX_DEBUG === "true"
? []
: [
[
"transform-remove-console",
{ exclude: ["error", "warn", "log", "info"] },
],
]),
],
}

24
transform.js Normal file
View File

@ -0,0 +1,24 @@
import babelJest from "babel-jest"
import baseConfig from "./thebabel.config.cjs"
/**
* Replace `import.meta` with `undefined`
*
* Needed to support server-side CJS in Jest
* that access `@remix-run/react`, where `import.meta.hot`
* is used for HMR.
*/
let metaPlugin = ({ types: t }) => ({
visitor: {
MetaProperty: (path) => {
path.replaceWith(t.identifier("undefined"));
},
},
});
export default babelJest.createTransformer({
babelrc: false,
...baseConfig,
plugins: [...baseConfig.plugins, metaPlugin],
});

View File

@ -1,33 +1,19 @@
{
"include": [
"**/*.ts",
"**/*.tsx",
"**/.server/**/*.ts",
"**/.server/**/*.tsx",
"**/.client/**/*.ts",
"**/.client/**/*.tsx"
],
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["dist", "__tests__", "node_modules"],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"types": ["@remix-run/node", "vite/client"],
"isolatedModules": true,
"esModuleInterop": true,
"jsx": "react-jsx",
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"target": "ES2022",
"strict": true,
"allowJs": true,
"module": "ES2022",
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"~/*": ["./app/*"]
},
// Vite takes care of building everything, not tsc.
"noEmit": true
"moduleResolution": "Bundler",
"allowSyntheticDefaultImports": true,
"strict": true,
"jsx": "react",
"declaration": true,
"emitDeclarationOnly": true,
"rootDir": ".",
"outDir": "../../build/node_modules/@remix-run/testing/dist"
}
}
}