Reformat.

This commit is contained in:
Patrick Fic
2025-03-21 11:41:42 -07:00
parent 14e7c64eab
commit d14137dc44
34 changed files with 380 additions and 339 deletions

View File

@@ -1,17 +0,0 @@
export default {
printWidth: 120,
useTabs: false,
tabWidth: 2,
trailingComma: "none",
semi: true,
singleQuote: false,
bracketSpacing: true,
arrowParens: "always",
jsxSingleQuote: false,
bracketSameLine: false,
endOfLine: "lf"
// importOrder: ["^@core/(.*)$", "^@server/(.*)$", "^@ui/(.*)$", "^[./]"],
// importOrderSeparation: true,
// importOrderSortSpecifiers: true
};

View File

@@ -3,12 +3,12 @@ productName: Shop Partner
directories:
buildResources: build
files:
- '!**/.vscode/*'
- '!src/*'
- '!electron.vite.config.{js,ts,mjs,cjs}'
- '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
- "!**/.vscode/*"
- "!src/*"
- "!electron.vite.config.{js,ts,mjs,cjs}"
- "!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}"
- "!{.env,.env.*,.npmrc,pnpm-lock.yaml}"
- "!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}"
asarUnpack:
- resources/**
win:

View File

@@ -1,20 +1,20 @@
import { resolve } from 'path'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import react from '@vitejs/plugin-react'
import { resolve } from "path";
import { defineConfig, externalizeDepsPlugin } from "electron-vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
main: {
plugins: [externalizeDepsPlugin()]
plugins: [externalizeDepsPlugin()],
},
preload: {
plugins: [externalizeDepsPlugin()]
plugins: [externalizeDepsPlugin()],
},
renderer: {
resolve: {
alias: {
'@renderer': resolve('src/renderer/src')
}
"@renderer": resolve("src/renderer/src"),
},
plugins: [react()]
}
})
},
plugins: [react()],
},
});

View File

@@ -7,7 +7,7 @@ import store from "../store/store";
import { DecodedAd1, OwnerRecordInterface } from "./decode-ad1.interface";
const DecodeAD1 = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedAd1> => {
let dbf: DBFFile | null = null;
try {
@@ -147,7 +147,7 @@ const DecodeAD1 = async (
"INS_CT_PH",
"INS_CT_PHX",
"LOSS_CAT",
])
]),
);
//Copy specific logic for manipulation.

View File

@@ -6,7 +6,7 @@ import { DecodedAD2 } from "./decode-ad2.interface";
import errorTypeCheck from "../../util/errorTypeCheck";
const DecodeAD2 = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedAD2> => {
let dbf: DBFFile | null = null;
try {
@@ -135,7 +135,7 @@ const DecodeAD2 = async (
//"LOC_PH",
//"LOC_PHX",
//"LOC_EA",
])
]),
);
//Apply business logic transfomrations.

View File

@@ -6,7 +6,7 @@ import errorTypeCheck from "../../util/errorTypeCheck";
import { DecodedEnv } from "./decode-env.interface";
const DecodeEnv = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedEnv> => {
let dbf: DBFFile | null = null;
try {
@@ -32,7 +32,7 @@ const DecodeEnv = async (
//TODO: Several of these fields will fail. Should extend schema to capture them.
//"EST_SYSTEM",
"ESTFILE_ID",
])
]),
);
rawEnvData.ciecaid = rawEnvData.estfile_id;
delete rawEnvData.estfile_id;

View File

@@ -7,7 +7,7 @@ import store from "../store/store";
import { DecodedLin, DecodedLinLine } from "./decode-lin.interface";
const DecodeLin = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedLin> => {
let dbf: DBFFile | null = null;
try {
@@ -80,7 +80,7 @@ const DecodeLin = async (
"BETT_PCTG",
"BETT_AMT",
"BETT_TAX",
])
]),
);
//Apply line by line adjustments.
singleLineData.op_code_desc = opCodeData[singleLineData.lbr_op]?.desc;

View File

@@ -6,7 +6,7 @@ import errorTypeCheck from "../../util/errorTypeCheck";
import { DecodedPfh } from "./decode-pfh.interface";
const DecodePfh = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedPfh> => {
let dbf: DBFFile | null = null;
try {
@@ -50,7 +50,7 @@ const DecodePfh = async (
"ADJ_STRDIS",
//"ADJ_BTR_IN", //Remove
"TAX_PREDIS",
])
]),
);
//Apply business logic transfomrations.

View File

@@ -10,7 +10,7 @@ import {
} from "./decode-pfl.interface";
const DecodePfl = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedPfl> => {
let dbf: DBFFile | null = null;
try {
@@ -67,7 +67,7 @@ const DecodePfl = async (
"LBR_TX_IN4",
"LBR_TX_TY5",
"LBR_TX_IN5",
])
]),
);
//Apply line by line adjustments.
//Set the job.rate_<CIECA_TYPE> field based on the value.

View File

@@ -11,7 +11,7 @@ import {
} from "./decode-pfm.interface";
const DecodePfm = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedPfm> => {
let dbf: DBFFile | null = null;
try {
@@ -80,8 +80,8 @@ const DecodePfm = async (
"MAT_TX_IN4",
"MAT_TX_TY5",
"MAT_TX_IN5",
])
)
]),
),
);
//Also capture the whole object.
@@ -93,7 +93,7 @@ const DecodePfm = async (
//Apply line by line adjustments.
const mapaLine: DecodedPfmLine | undefined = rawPfmData.find(
(line) => line.matl_type === "MAPA"
(line) => line.matl_type === "MAPA",
);
if (mapaLine) {
jobMaterialRates.rate_mapa =
@@ -102,7 +102,7 @@ const DecodePfm = async (
}
const mashLine: DecodedPfmLine | undefined = rawPfmData.find(
(line) => line.matl_type === "MASH"
(line) => line.matl_type === "MASH",
);
if (mashLine) {
jobMaterialRates.rate_mash =
@@ -111,7 +111,7 @@ const DecodePfm = async (
}
const mahwLine: DecodedPfmLine | undefined = rawPfmData.find(
(line) => line.matl_type === "MAHW"
(line) => line.matl_type === "MAHW",
);
if (mahwLine) {
jobMaterialRates.rate_mahw =
@@ -122,7 +122,7 @@ const DecodePfm = async (
const additionalMaterials = ["MA2S", "MA2T", "MA3S", "MACS", "MABL"];
additionalMaterials.forEach((type) => {
const line: DecodedPfmLine | undefined = rawPfmData.find(
(line) => line.matl_type === type
(line) => line.matl_type === type,
);
if (line) {
jobMaterialRates[`rate_${type.toLowerCase()}`] =

View File

@@ -7,7 +7,7 @@ import YNBoolConverter from "../../util/ynBoolConverter";
import { DecodedPfo, DecodedPfoLine } from "./decode-pfo.interface";
const DecodePfo = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedPfo> => {
let dbf: DBFFile | null = null;
try {
@@ -58,8 +58,8 @@ const DecodePfo = async (
"STOR_T_IN5",
"STOR_T_TY6",
"STOR_T_IN6",
])
)
]),
),
);
//Apply business logic transfomrations.

View File

@@ -11,7 +11,7 @@ import {
} from "./decode-pfp.interface";
const DecodePfp = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedPfp> => {
let dbf: DBFFile | null = null;
try {
@@ -51,7 +51,7 @@ const DecodePfp = async (
"PRT_TX_IN4",
"PRT_TX_TY5",
"PRT_TX_IN5",
])
]),
);
singleLineData.prt_tax_rt = singleLineData.prt_tax_rt / 100;
@@ -66,7 +66,7 @@ const DecodePfp = async (
acc[line.prt_type] = line;
return acc;
},
{} as DecodedPfpLinesByType
{} as DecodedPfpLinesByType,
);
return { parts_tax_rates: parsedPfpFile };

View File

@@ -6,7 +6,7 @@ import errorTypeCheck from "../../util/errorTypeCheck";
import { DecodedPft, DecodedPftLine } from "./decode-pft.interface";
const DecodePft = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedPft> => {
let dbf: DBFFile | null = null;
try {
@@ -154,7 +154,7 @@ const DecodePft = async (
"TY6_THRES5",
"TY6_RATE5",
"TY6_SUR5",
])
]),
);
//Apply business logic transfomrations.

View File

@@ -6,7 +6,7 @@ import errorTypeCheck from "../../util/errorTypeCheck";
import { DecodedTtl, DecodedTtlLine } from "./decode-ttl.interface";
const DecodeTtl = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedTtl> => {
let dbf: DBFFile | null = null;
try {
@@ -42,7 +42,7 @@ const DecodeTtl = async (
"G_TTL_DISC",
"G_TAX",
"GST_AMT",
])
]),
);
//Apply business logic transfomrations.

View File

@@ -7,7 +7,7 @@ import errorTypeCheck from "../../util/errorTypeCheck";
import store from "../store/store";
const DecodeVeh = async (
extensionlessFilePath: string
extensionlessFilePath: string,
): Promise<DecodedVeh> => {
let dbf: DBFFile | null = null;
try {
@@ -56,7 +56,7 @@ const DecodeVeh = async (
"PAINT_CD1",
"PAINT_CD2",
"PAINT_CD3",
])
]),
);
//Apply business logic transfomrations.

View File

@@ -10,7 +10,7 @@ const requestMiddleware: RequestMiddleware = async (request) => {
`%c[Graphql Request]%c${request.operationName}`,
"color: red",
"color: green",
request
request,
);
return {
@@ -23,7 +23,7 @@ const client: GraphQLClient = new GraphQLClient(
import.meta.env.VITE_GRAPHQL_ENDPOINT,
{
requestMiddleware,
}
},
);
export async function getTokenFromRenderer(): Promise<string> {
@@ -35,7 +35,7 @@ export async function getTokenFromRenderer(): Promise<string> {
} catch (error) {
log.error(
"Unable to send request to renderer process for token",
errorTypeCheck(error)
errorTypeCheck(error),
);
}

View File

@@ -154,7 +154,7 @@ function createWindow(): void {
label: "Log the Store",
click: (): void => {
log.debug(
"Store Contents" + JSON.stringify(store.store, null, 4)
"Store Contents" + JSON.stringify(store.store, null, 4),
);
},
},
@@ -171,7 +171,7 @@ function createWindow(): void {
jobs
{
id}}
`
`,
)
.then((data) => {
log.info("Data from graffle", data);

View File

@@ -27,7 +27,7 @@ const logIpcMessages = (): void => {
`%c[IPC Main]%c${messageType}`,
"color: red",
"color: green",
payload
payload,
);
// Call original handler if it existed
if (originalHandler) {
@@ -38,7 +38,7 @@ const logIpcMessages = (): void => {
};
ipcMain.on(ipcTypes.toMain.test, () =>
console.log("** Verify that ipcMain is loaded and working.")
console.log("** Verify that ipcMain is loaded and working."),
);
//Auth handler
@@ -67,15 +67,15 @@ if (import.meta.env.DEV) {
//Settings Handlers
ipcMain.handle(
ipcTypes.toMain.settings.filepaths.get,
SettingsWatchedFilePathsGet
SettingsWatchedFilePathsGet,
);
ipcMain.handle(
ipcTypes.toMain.settings.filepaths.add,
SettingsWatchedFilePathsAdd
SettingsWatchedFilePathsAdd,
);
ipcMain.handle(
ipcTypes.toMain.settings.filepaths.remove,
SettingsWatchedFilePathsRemove
SettingsWatchedFilePathsRemove,
);
//Watcher Handlers

View File

@@ -17,7 +17,7 @@ const SettingsWatchedFilePathsAdd = async (): Promise<string[]> => {
if (!result.canceled) {
Store.set(
"settings.filepaths",
_.union(result.filePaths, Store.get("settings.filepaths"))
_.union(result.filePaths, Store.get("settings.filepaths")),
);
addWatcherPath(result.filePaths);
}
@@ -26,11 +26,11 @@ const SettingsWatchedFilePathsAdd = async (): Promise<string[]> => {
};
const SettingsWatchedFilePathsRemove = async (
event: IpcMainInvokeEvent,
path: string
path: string,
): Promise<string[]> => {
Store.set(
"settings.filepaths",
_.without(Store.get("settings.filepaths"), path)
_.without(Store.get("settings.filepaths"), path),
);
removeWatcherPath(path);
return Store.get("settings.filepaths");

View File

@@ -12,14 +12,14 @@ import log from "electron-log/main";
const ipcMainHandleAuthStateChanged = async (
event: IpcMainEvent,
user: User | null
user: User | null,
): Promise<void> => {
Store.set("user", user);
//Need to query the currently active shop, and store the metadata as well.
//Also need to query the OP Codes for decoding reference.
const activeBodyshop: ActiveBodyshopQueryResult = await client.request(
QUERY_ACTIVE_BODYSHOP_TYPED
QUERY_ACTIVE_BODYSHOP_TYPED,
);
Store.set("app.bodyshop", activeBodyshop.bodyshops[0]);
@@ -28,7 +28,7 @@ const ipcMainHandleAuthStateChanged = async (
QUERY_MASTERDATA_TYPED,
{
key: `${activeBodyshop.bodyshops[0].region_config}_ciecaopcodes`,
}
},
);
Store.set("app.masterdata.opcodes", JSON.parse(OpCodes.masterdata[0]?.value));
log.debug("Received authentication state change from Renderer.", user);

View File

@@ -1,8 +1,8 @@
import { ElectronAPI } from '@electron-toolkit/preload'
import { ElectronAPI } from "@electron-toolkit/preload";
declare global {
interface Window {
electron: ElectronAPI
api: unknown
electron: ElectronAPI;
api: unknown;
}
}

View File

@@ -1,23 +1,23 @@
import { contextBridge } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import 'electron-log/preload'
import { contextBridge } from "electron";
import { electronAPI } from "@electron-toolkit/preload";
import "electron-log/preload";
// Custom APIs for renderer
const api = {}
const api = {};
// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld('electron', electronAPI)
contextBridge.exposeInMainWorld('api', api)
contextBridge.exposeInMainWorld("electron", electronAPI);
contextBridge.exposeInMainWorld("api", api);
} catch (error) {
console.error(error)
console.error(error);
}
} else {
// @ts-ignore (define in dts)
window.electron = electronAPI
window.electron = electronAPI;
// @ts-ignore (define in dts)
window.api = api
window.api = api;
}

View File

@@ -1,21 +1,21 @@
import { test, expect } from '@playwright/test';
import { Page } from '@playwright/test';
import { test, expect } from "@playwright/test";
import { Page } from "@playwright/test";
// src/renderer/src/App.test.tsx
// Mock data
const mockUser = {
uid: 'test123',
email: 'test@example.com',
displayName: 'Test User',
uid: "test123",
email: "test@example.com",
displayName: "Test User",
toJSON: () => ({
uid: 'test123',
email: 'test@example.com',
displayName: 'Test User'
})
uid: "test123",
email: "test@example.com",
displayName: "Test User",
}),
};
test.describe('App Component', () => {
test.describe("App Component", () => {
let page: Page;
test.beforeEach(async ({ browser }) => {
@@ -26,28 +26,28 @@ test.describe('App Component', () => {
window.mockAuthState = null;
// Mock the firebase auth module
jest.mock('./util/firebase', () => ({
jest.mock("./util/firebase", () => ({
auth: {
onAuthStateChanged: (callback) => {
callback(window.mockAuthState);
// Return mock unsubscribe function
return () => {};
}
}
},
},
}));
// Mock electron IPC
window.electron = {
ipcRenderer: {
send: jest.fn()
}
send: jest.fn(),
},
};
});
await page.goto('/');
await page.goto("/");
});
test('should show SignInForm when user is not authenticated', async () => {
test("should show SignInForm when user is not authenticated", async () => {
await page.evaluate(() => {
window.mockAuthState = null;
});
@@ -55,11 +55,13 @@ test.describe('App Component', () => {
await page.reload();
// Check if SignInForm is visible
const signInForm = await page.locator('form').filter({ hasText: 'Sign In' });
const signInForm = await page
.locator("form")
.filter({ hasText: "Sign In" });
await expect(signInForm).toBeVisible();
});
test('should show routes when user is authenticated', async () => {
test("should show routes when user is authenticated", async () => {
await page.evaluate((user) => {
window.mockAuthState = user;
}, mockUser);
@@ -71,12 +73,14 @@ test.describe('App Component', () => {
await expect(authHome).toBeVisible();
// Check that electron IPC was called with auth state
await expect(page.evaluate(() => {
await expect(
page.evaluate(() => {
return window.electron.ipcRenderer.send.mock.calls.length > 0;
})).resolves.toBe(true);
}),
).resolves.toBe(true);
});
test('should navigate to settings page when authenticated', async () => {
test("should navigate to settings page when authenticated", async () => {
await page.evaluate((user) => {
window.mockAuthState = user;
}, mockUser);

View File

@@ -25,7 +25,7 @@ const App: React.FC = () => {
if (user) {
window.electron.ipcRenderer.send(
ipcTypes.toMain.authStateChanged,
user.toJSON()
user.toJSON(),
);
window.electron.ipcRenderer.send(ipcTypes.toMain.watcher.start);
}

View File

@@ -8,7 +8,7 @@ const Home: React.FC = () => {
<Button
onClick={(): void => {
window.electron.ipcRenderer.send(
ipcTypes.toMain.debug.decodeEstimate
ipcTypes.toMain.debug.decodeEstimate,
);
}}
>

View File

@@ -24,7 +24,7 @@ const SignInForm: React.FC = () => {
};
const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
errorInfo
errorInfo,
) => {
log.log("Failed:", errorInfo);
};

View File

@@ -1,7 +1,7 @@
import { useState } from 'react'
import { useState } from "react";
function Versions(): JSX.Element {
const [versions] = useState(window.electron.process.versions)
const [versions] = useState(window.electron.process.versions);
return (
<ul className="versions">
@@ -9,7 +9,7 @@ function Versions(): JSX.Element {
<li className="chrome-version">Chromium v{versions.chrome}</li>
<li className="node-version">Node v{versions.node}</li>
</ul>
)
);
}
export default Versions
export default Versions;

View File

@@ -7,5 +7,5 @@ import "./util/ipcRendererHandler";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
</React.StrictMode>,
);

View File

@@ -16,7 +16,7 @@ ipcRenderer.on(
(event: Electron.IpcRendererEvent, arg) => {
console.log("Received test message from main process");
console.log(arg);
}
},
);
ipcRenderer.on(
@@ -24,7 +24,7 @@ ipcRenderer.on(
async (event: Electron.IpcRendererEvent, arg) => {
const token = await auth.currentUser?.getIdToken();
ipcRenderer.send(ipcTypes.toMain.user.getTokenResponse, token);
}
},
);
ipcRenderer.on(
@@ -33,7 +33,7 @@ ipcRenderer.on(
console.log("Watcher has started");
console.log(arg);
dispatch(watcherStarted());
}
},
);
ipcRenderer.on(
@@ -42,7 +42,7 @@ ipcRenderer.on(
console.log("Watcher has stopped");
console.log(arg);
dispatch(watcherStopped());
}
},
);
ipcRenderer.on(
ipcTypes.toRenderer.watcher.error,
@@ -50,5 +50,5 @@ ipcRenderer.on(
console.log("Watcher has encountered an error");
console.log(error);
dispatch(watcherError(error));
}
},
);

View File

@@ -30,7 +30,7 @@ function deepLowerCaseKeys<T = any>(obj: any): T {
return result;
},
{} as Record<string, any>
{} as Record<string, any>,
) as T;
}
export default deepLowerCaseKeys;

View File

@@ -1,75 +1,77 @@
import { test, expect, type Page } from '@playwright/test';
import { test, expect, type Page } from "@playwright/test";
test.beforeEach(async ({ page }) => {
await page.goto('https://demo.playwright.dev/todomvc');
await page.goto("https://demo.playwright.dev/todomvc");
});
const TODO_ITEMS = [
'buy some cheese',
'feed the cat',
'book a doctors appointment'
"buy some cheese",
"feed the cat",
"book a doctors appointment",
] as const;
test.describe('New Todo', () => {
test('should allow me to add todo items', async ({ page }) => {
test.describe("New Todo", () => {
test("should allow me to add todo items", async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
const newTodo = page.getByPlaceholder("What needs to be done?");
// Create 1st todo.
await newTodo.fill(TODO_ITEMS[0]);
await newTodo.press('Enter');
await newTodo.press("Enter");
// Make sure the list only has one todo item.
await expect(page.getByTestId('todo-title')).toHaveText([
TODO_ITEMS[0]
]);
await expect(page.getByTestId("todo-title")).toHaveText([TODO_ITEMS[0]]);
// Create 2nd todo.
await newTodo.fill(TODO_ITEMS[1]);
await newTodo.press('Enter');
await newTodo.press("Enter");
// Make sure the list now has two todo items.
await expect(page.getByTestId('todo-title')).toHaveText([
await expect(page.getByTestId("todo-title")).toHaveText([
TODO_ITEMS[0],
TODO_ITEMS[1]
TODO_ITEMS[1],
]);
await checkNumberOfTodosInLocalStorage(page, 2);
});
test('should clear text input field when an item is added', async ({ page }) => {
test("should clear text input field when an item is added", async ({
page,
}) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
const newTodo = page.getByPlaceholder("What needs to be done?");
// Create one todo item.
await newTodo.fill(TODO_ITEMS[0]);
await newTodo.press('Enter');
await newTodo.press("Enter");
// Check that input is empty.
await expect(newTodo).toBeEmpty();
await checkNumberOfTodosInLocalStorage(page, 1);
});
test('should append new items to the bottom of the list', async ({ page }) => {
test("should append new items to the bottom of the list", async ({
page,
}) => {
// Create 3 items.
await createDefaultTodos(page);
// create a todo count locator
const todoCount = page.getByTestId('todo-count')
const todoCount = page.getByTestId("todo-count");
// Check test using different methods.
await expect(page.getByText('3 items left')).toBeVisible();
await expect(todoCount).toHaveText('3 items left');
await expect(todoCount).toContainText('3');
await expect(page.getByText("3 items left")).toBeVisible();
await expect(todoCount).toHaveText("3 items left");
await expect(todoCount).toContainText("3");
await expect(todoCount).toHaveText(/3/);
// Check all items in one call.
await expect(page.getByTestId('todo-title')).toHaveText(TODO_ITEMS);
await expect(page.getByTestId("todo-title")).toHaveText(TODO_ITEMS);
await checkNumberOfTodosInLocalStorage(page, 3);
});
});
test.describe('Mark all as completed', () => {
test.describe("Mark all as completed", () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
await checkNumberOfTodosInLocalStorage(page, 3);
@@ -79,39 +81,47 @@ test.describe('Mark all as completed', () => {
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should allow me to mark all items as completed', async ({ page }) => {
test("should allow me to mark all items as completed", async ({ page }) => {
// Complete all todos.
await page.getByLabel('Mark all as complete').check();
await page.getByLabel("Mark all as complete").check();
// Ensure all todos have 'completed' class.
await expect(page.getByTestId('todo-item')).toHaveClass(['completed', 'completed', 'completed']);
await expect(page.getByTestId("todo-item")).toHaveClass([
"completed",
"completed",
"completed",
]);
await checkNumberOfCompletedTodosInLocalStorage(page, 3);
});
test('should allow me to clear the complete state of all items', async ({ page }) => {
const toggleAll = page.getByLabel('Mark all as complete');
test("should allow me to clear the complete state of all items", async ({
page,
}) => {
const toggleAll = page.getByLabel("Mark all as complete");
// Check and then immediately uncheck.
await toggleAll.check();
await toggleAll.uncheck();
// Should be no completed classes.
await expect(page.getByTestId('todo-item')).toHaveClass(['', '', '']);
await expect(page.getByTestId("todo-item")).toHaveClass(["", "", ""]);
});
test('complete all checkbox should update state when items are completed / cleared', async ({ page }) => {
const toggleAll = page.getByLabel('Mark all as complete');
test("complete all checkbox should update state when items are completed / cleared", async ({
page,
}) => {
const toggleAll = page.getByLabel("Mark all as complete");
await toggleAll.check();
await expect(toggleAll).toBeChecked();
await checkNumberOfCompletedTodosInLocalStorage(page, 3);
// Uncheck first todo.
const firstTodo = page.getByTestId('todo-item').nth(0);
await firstTodo.getByRole('checkbox').uncheck();
const firstTodo = page.getByTestId("todo-item").nth(0);
await firstTodo.getByRole("checkbox").uncheck();
// Reuse toggleAll locator and make sure its not checked.
await expect(toggleAll).not.toBeChecked();
await firstTodo.getByRole('checkbox').check();
await firstTodo.getByRole("checkbox").check();
await checkNumberOfCompletedTodosInLocalStorage(page, 3);
// Assert the toggle all is checked again.
@@ -119,205 +129,236 @@ test.describe('Mark all as completed', () => {
});
});
test.describe('Item', () => {
test('should allow me to mark items as complete', async ({ page }) => {
test.describe("Item", () => {
test("should allow me to mark items as complete", async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
const newTodo = page.getByPlaceholder("What needs to be done?");
// Create two items.
for (const item of TODO_ITEMS.slice(0, 2)) {
await newTodo.fill(item);
await newTodo.press('Enter');
await newTodo.press("Enter");
}
// Check first item.
const firstTodo = page.getByTestId('todo-item').nth(0);
await firstTodo.getByRole('checkbox').check();
await expect(firstTodo).toHaveClass('completed');
const firstTodo = page.getByTestId("todo-item").nth(0);
await firstTodo.getByRole("checkbox").check();
await expect(firstTodo).toHaveClass("completed");
// Check second item.
const secondTodo = page.getByTestId('todo-item').nth(1);
await expect(secondTodo).not.toHaveClass('completed');
await secondTodo.getByRole('checkbox').check();
const secondTodo = page.getByTestId("todo-item").nth(1);
await expect(secondTodo).not.toHaveClass("completed");
await secondTodo.getByRole("checkbox").check();
// Assert completed class.
await expect(firstTodo).toHaveClass('completed');
await expect(secondTodo).toHaveClass('completed');
await expect(firstTodo).toHaveClass("completed");
await expect(secondTodo).toHaveClass("completed");
});
test('should allow me to un-mark items as complete', async ({ page }) => {
test("should allow me to un-mark items as complete", async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
const newTodo = page.getByPlaceholder("What needs to be done?");
// Create two items.
for (const item of TODO_ITEMS.slice(0, 2)) {
await newTodo.fill(item);
await newTodo.press('Enter');
await newTodo.press("Enter");
}
const firstTodo = page.getByTestId('todo-item').nth(0);
const secondTodo = page.getByTestId('todo-item').nth(1);
const firstTodoCheckbox = firstTodo.getByRole('checkbox');
const firstTodo = page.getByTestId("todo-item").nth(0);
const secondTodo = page.getByTestId("todo-item").nth(1);
const firstTodoCheckbox = firstTodo.getByRole("checkbox");
await firstTodoCheckbox.check();
await expect(firstTodo).toHaveClass('completed');
await expect(secondTodo).not.toHaveClass('completed');
await expect(firstTodo).toHaveClass("completed");
await expect(secondTodo).not.toHaveClass("completed");
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await firstTodoCheckbox.uncheck();
await expect(firstTodo).not.toHaveClass('completed');
await expect(secondTodo).not.toHaveClass('completed');
await expect(firstTodo).not.toHaveClass("completed");
await expect(secondTodo).not.toHaveClass("completed");
await checkNumberOfCompletedTodosInLocalStorage(page, 0);
});
test('should allow me to edit an item', async ({ page }) => {
test("should allow me to edit an item", async ({ page }) => {
await createDefaultTodos(page);
const todoItems = page.getByTestId('todo-item');
const todoItems = page.getByTestId("todo-item");
const secondTodo = todoItems.nth(1);
await secondTodo.dblclick();
await expect(secondTodo.getByRole('textbox', { name: 'Edit' })).toHaveValue(TODO_ITEMS[1]);
await secondTodo.getByRole('textbox', { name: 'Edit' }).fill('buy some sausages');
await secondTodo.getByRole('textbox', { name: 'Edit' }).press('Enter');
await expect(secondTodo.getByRole("textbox", { name: "Edit" })).toHaveValue(
TODO_ITEMS[1],
);
await secondTodo
.getByRole("textbox", { name: "Edit" })
.fill("buy some sausages");
await secondTodo.getByRole("textbox", { name: "Edit" }).press("Enter");
// Explicitly assert the new text value.
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
'buy some sausages',
TODO_ITEMS[2]
"buy some sausages",
TODO_ITEMS[2],
]);
await checkTodosInLocalStorage(page, 'buy some sausages');
await checkTodosInLocalStorage(page, "buy some sausages");
});
});
test.describe('Editing', () => {
test.describe("Editing", () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should hide other controls when editing', async ({ page }) => {
const todoItem = page.getByTestId('todo-item').nth(1);
test("should hide other controls when editing", async ({ page }) => {
const todoItem = page.getByTestId("todo-item").nth(1);
await todoItem.dblclick();
await expect(todoItem.getByRole('checkbox')).not.toBeVisible();
await expect(todoItem.locator('label', {
await expect(todoItem.getByRole("checkbox")).not.toBeVisible();
await expect(
todoItem.locator("label", {
hasText: TODO_ITEMS[1],
})).not.toBeVisible();
}),
).not.toBeVisible();
await checkNumberOfTodosInLocalStorage(page, 3);
});
test('should save edits on blur', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
test("should save edits on blur", async ({ page }) => {
const todoItems = page.getByTestId("todo-item");
await todoItems.nth(1).dblclick();
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages');
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).dispatchEvent('blur');
await todoItems
.nth(1)
.getByRole("textbox", { name: "Edit" })
.fill("buy some sausages");
await todoItems
.nth(1)
.getByRole("textbox", { name: "Edit" })
.dispatchEvent("blur");
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
'buy some sausages',
"buy some sausages",
TODO_ITEMS[2],
]);
await checkTodosInLocalStorage(page, 'buy some sausages');
await checkTodosInLocalStorage(page, "buy some sausages");
});
test('should trim entered text', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
test("should trim entered text", async ({ page }) => {
const todoItems = page.getByTestId("todo-item");
await todoItems.nth(1).dblclick();
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill(' buy some sausages ');
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter');
await todoItems
.nth(1)
.getByRole("textbox", { name: "Edit" })
.fill(" buy some sausages ");
await todoItems
.nth(1)
.getByRole("textbox", { name: "Edit" })
.press("Enter");
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
'buy some sausages',
"buy some sausages",
TODO_ITEMS[2],
]);
await checkTodosInLocalStorage(page, 'buy some sausages');
await checkTodosInLocalStorage(page, "buy some sausages");
});
test('should remove the item if an empty text string was entered', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
test("should remove the item if an empty text string was entered", async ({
page,
}) => {
const todoItems = page.getByTestId("todo-item");
await todoItems.nth(1).dblclick();
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('');
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter');
await todoItems.nth(1).getByRole("textbox", { name: "Edit" }).fill("");
await todoItems
.nth(1)
.getByRole("textbox", { name: "Edit" })
.press("Enter");
await expect(todoItems).toHaveText([
TODO_ITEMS[0],
TODO_ITEMS[2],
]);
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);
});
test('should cancel edits on escape', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
test("should cancel edits on escape", async ({ page }) => {
const todoItems = page.getByTestId("todo-item");
await todoItems.nth(1).dblclick();
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages');
await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Escape');
await todoItems
.nth(1)
.getByRole("textbox", { name: "Edit" })
.fill("buy some sausages");
await todoItems
.nth(1)
.getByRole("textbox", { name: "Edit" })
.press("Escape");
await expect(todoItems).toHaveText(TODO_ITEMS);
});
});
test.describe('Counter', () => {
test('should display the current number of todo items', async ({ page }) => {
test.describe("Counter", () => {
test("should display the current number of todo items", async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
const newTodo = page.getByPlaceholder("What needs to be done?");
// create a todo count locator
const todoCount = page.getByTestId('todo-count')
const todoCount = page.getByTestId("todo-count");
await newTodo.fill(TODO_ITEMS[0]);
await newTodo.press('Enter');
await newTodo.press("Enter");
await expect(todoCount).toContainText('1');
await expect(todoCount).toContainText("1");
await newTodo.fill(TODO_ITEMS[1]);
await newTodo.press('Enter');
await expect(todoCount).toContainText('2');
await newTodo.press("Enter");
await expect(todoCount).toContainText("2");
await checkNumberOfTodosInLocalStorage(page, 2);
});
});
test.describe('Clear completed button', () => {
test.describe("Clear completed button", () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
});
test('should display the correct text', async ({ page }) => {
await page.locator('.todo-list li .toggle').first().check();
await expect(page.getByRole('button', { name: 'Clear completed' })).toBeVisible();
test("should display the correct text", async ({ page }) => {
await page.locator(".todo-list li .toggle").first().check();
await expect(
page.getByRole("button", { name: "Clear completed" }),
).toBeVisible();
});
test('should remove completed items when clicked', async ({ page }) => {
const todoItems = page.getByTestId('todo-item');
await todoItems.nth(1).getByRole('checkbox').check();
await page.getByRole('button', { name: 'Clear completed' }).click();
test("should remove completed items when clicked", async ({ page }) => {
const todoItems = page.getByTestId("todo-item");
await todoItems.nth(1).getByRole("checkbox").check();
await page.getByRole("button", { name: "Clear completed" }).click();
await expect(todoItems).toHaveCount(2);
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);
});
test('should be hidden when there are no items that are completed', async ({ page }) => {
await page.locator('.todo-list li .toggle').first().check();
await page.getByRole('button', { name: 'Clear completed' }).click();
await expect(page.getByRole('button', { name: 'Clear completed' })).toBeHidden();
test("should be hidden when there are no items that are completed", async ({
page,
}) => {
await page.locator(".todo-list li .toggle").first().check();
await page.getByRole("button", { name: "Clear completed" }).click();
await expect(
page.getByRole("button", { name: "Clear completed" }),
).toBeHidden();
});
});
test.describe('Persistence', () => {
test('should persist its data', async ({ page }) => {
test.describe("Persistence", () => {
test("should persist its data", async ({ page }) => {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
const newTodo = page.getByPlaceholder("What needs to be done?");
for (const item of TODO_ITEMS.slice(0, 2)) {
await newTodo.fill(item);
await newTodo.press('Enter');
await newTodo.press("Enter");
}
const todoItems = page.getByTestId('todo-item');
const firstTodoCheck = todoItems.nth(0).getByRole('checkbox');
const todoItems = page.getByTestId("todo-item");
const firstTodoCheck = todoItems.nth(0).getByRole("checkbox");
await firstTodoCheck.check();
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);
await expect(firstTodoCheck).toBeChecked();
await expect(todoItems).toHaveClass(['completed', '']);
await expect(todoItems).toHaveClass(["completed", ""]);
// Ensure there is 1 completed item.
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
@@ -326,11 +367,11 @@ test.describe('Persistence', () => {
await page.reload();
await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);
await expect(firstTodoCheck).toBeChecked();
await expect(todoItems).toHaveClass(['completed', '']);
await expect(todoItems).toHaveClass(["completed", ""]);
});
});
test.describe('Routing', () => {
test.describe("Routing", () => {
test.beforeEach(async ({ page }) => {
await createDefaultTodos(page);
// make sure the app had a chance to save updated todos in storage
@@ -339,33 +380,33 @@ test.describe('Routing', () => {
await checkTodosInLocalStorage(page, TODO_ITEMS[0]);
});
test('should allow me to display active items', async ({ page }) => {
const todoItem = page.getByTestId('todo-item');
await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();
test("should allow me to display active items", async ({ page }) => {
const todoItem = page.getByTestId("todo-item");
await page.getByTestId("todo-item").nth(1).getByRole("checkbox").check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await page.getByRole('link', { name: 'Active' }).click();
await page.getByRole("link", { name: "Active" }).click();
await expect(todoItem).toHaveCount(2);
await expect(todoItem).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);
});
test('should respect the back button', async ({ page }) => {
const todoItem = page.getByTestId('todo-item');
await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();
test("should respect the back button", async ({ page }) => {
const todoItem = page.getByTestId("todo-item");
await page.getByTestId("todo-item").nth(1).getByRole("checkbox").check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await test.step('Showing all items', async () => {
await page.getByRole('link', { name: 'All' }).click();
await test.step("Showing all items", async () => {
await page.getByRole("link", { name: "All" }).click();
await expect(todoItem).toHaveCount(3);
});
await test.step('Showing active items', async () => {
await page.getByRole('link', { name: 'Active' }).click();
await test.step("Showing active items", async () => {
await page.getByRole("link", { name: "Active" }).click();
});
await test.step('Showing completed items', async () => {
await page.getByRole('link', { name: 'Completed' }).click();
await test.step("Showing completed items", async () => {
await page.getByRole("link", { name: "Completed" }).click();
});
await expect(todoItem).toHaveCount(1);
@@ -375,63 +416,74 @@ test.describe('Routing', () => {
await expect(todoItem).toHaveCount(3);
});
test('should allow me to display completed items', async ({ page }) => {
await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();
test("should allow me to display completed items", async ({ page }) => {
await page.getByTestId("todo-item").nth(1).getByRole("checkbox").check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await page.getByRole('link', { name: 'Completed' }).click();
await expect(page.getByTestId('todo-item')).toHaveCount(1);
await page.getByRole("link", { name: "Completed" }).click();
await expect(page.getByTestId("todo-item")).toHaveCount(1);
});
test('should allow me to display all items', async ({ page }) => {
await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();
test("should allow me to display all items", async ({ page }) => {
await page.getByTestId("todo-item").nth(1).getByRole("checkbox").check();
await checkNumberOfCompletedTodosInLocalStorage(page, 1);
await page.getByRole('link', { name: 'Active' }).click();
await page.getByRole('link', { name: 'Completed' }).click();
await page.getByRole('link', { name: 'All' }).click();
await expect(page.getByTestId('todo-item')).toHaveCount(3);
await page.getByRole("link", { name: "Active" }).click();
await page.getByRole("link", { name: "Completed" }).click();
await page.getByRole("link", { name: "All" }).click();
await expect(page.getByTestId("todo-item")).toHaveCount(3);
});
test('should highlight the currently applied filter', async ({ page }) => {
await expect(page.getByRole('link', { name: 'All' })).toHaveClass('selected');
test("should highlight the currently applied filter", async ({ page }) => {
await expect(page.getByRole("link", { name: "All" })).toHaveClass(
"selected",
);
//create locators for active and completed links
const activeLink = page.getByRole('link', { name: 'Active' });
const completedLink = page.getByRole('link', { name: 'Completed' });
const activeLink = page.getByRole("link", { name: "Active" });
const completedLink = page.getByRole("link", { name: "Completed" });
await activeLink.click();
// Page change - active items.
await expect(activeLink).toHaveClass('selected');
await expect(activeLink).toHaveClass("selected");
await completedLink.click();
// Page change - completed items.
await expect(completedLink).toHaveClass('selected');
await expect(completedLink).toHaveClass("selected");
});
});
async function createDefaultTodos(page: Page) {
// create a new todo locator
const newTodo = page.getByPlaceholder('What needs to be done?');
const newTodo = page.getByPlaceholder("What needs to be done?");
for (const item of TODO_ITEMS) {
await newTodo.fill(item);
await newTodo.press('Enter');
await newTodo.press("Enter");
}
}
async function checkNumberOfTodosInLocalStorage(page: Page, expected: number) {
return await page.waitForFunction(e => {
return JSON.parse(localStorage['react-todos']).length === e;
return await page.waitForFunction((e) => {
return JSON.parse(localStorage["react-todos"]).length === e;
}, expected);
}
async function checkNumberOfCompletedTodosInLocalStorage(page: Page, expected: number) {
return await page.waitForFunction(e => {
return JSON.parse(localStorage['react-todos']).filter((todo: any) => todo.completed).length === e;
async function checkNumberOfCompletedTodosInLocalStorage(
page: Page,
expected: number,
) {
return await page.waitForFunction((e) => {
return (
JSON.parse(localStorage["react-todos"]).filter(
(todo: any) => todo.completed,
).length === e
);
}, expected);
}
async function checkTodosInLocalStorage(page: Page, title: string) {
return await page.waitForFunction(t => {
return JSON.parse(localStorage['react-todos']).map((todo: any) => todo.title).includes(t);
return await page.waitForFunction((t) => {
return JSON.parse(localStorage["react-todos"])
.map((todo: any) => todo.title)
.includes(t);
}, title);
}

View File

@@ -1,18 +1,20 @@
import { test, expect } from '@playwright/test';
import { test, expect } from "@playwright/test";
test('has title', async ({ page }) => {
await page.goto('https://playwright.dev/');
test("has title", async ({ page }) => {
await page.goto("https://playwright.dev/");
// Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/);
});
test('get started link', async ({ page }) => {
await page.goto('https://playwright.dev/');
test("get started link", async ({ page }) => {
await page.goto("https://playwright.dev/");
// Click the get started link.
await page.getByRole('link', { name: 'Get started' }).click();
await page.getByRole("link", { name: "Get started" }).click();
// Expects page to have a heading with the name of Installation.
await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
await expect(
page.getByRole("heading", { name: "Installation" }),
).toBeVisible();
});