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: directories:
buildResources: build buildResources: build
files: files:
- '!**/.vscode/*' - "!**/.vscode/*"
- '!src/*' - "!src/*"
- '!electron.vite.config.{js,ts,mjs,cjs}' - "!electron.vite.config.{js,ts,mjs,cjs}"
- '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}' - "!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}"
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}' - "!{.env,.env.*,.npmrc,pnpm-lock.yaml}"
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}' - "!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}"
asarUnpack: asarUnpack:
- resources/** - resources/**
win: win:

View File

@@ -1,20 +1,20 @@
import { resolve } from 'path' import { resolve } from "path";
import { defineConfig, externalizeDepsPlugin } from 'electron-vite' import { defineConfig, externalizeDepsPlugin } from "electron-vite";
import react from '@vitejs/plugin-react' import react from "@vitejs/plugin-react";
export default defineConfig({ export default defineConfig({
main: { main: {
plugins: [externalizeDepsPlugin()] plugins: [externalizeDepsPlugin()],
}, },
preload: { preload: {
plugins: [externalizeDepsPlugin()] plugins: [externalizeDepsPlugin()],
}, },
renderer: { renderer: {
resolve: { resolve: {
alias: { 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"; import { DecodedAd1, OwnerRecordInterface } from "./decode-ad1.interface";
const DecodeAD1 = async ( const DecodeAD1 = async (
extensionlessFilePath: string extensionlessFilePath: string,
): Promise<DecodedAd1> => { ): Promise<DecodedAd1> => {
let dbf: DBFFile | null = null; let dbf: DBFFile | null = null;
try { try {
@@ -147,7 +147,7 @@ const DecodeAD1 = async (
"INS_CT_PH", "INS_CT_PH",
"INS_CT_PHX", "INS_CT_PHX",
"LOSS_CAT", "LOSS_CAT",
]) ]),
); );
//Copy specific logic for manipulation. //Copy specific logic for manipulation.

View File

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

View File

@@ -6,7 +6,7 @@ import errorTypeCheck from "../../util/errorTypeCheck";
import { DecodedEnv } from "./decode-env.interface"; import { DecodedEnv } from "./decode-env.interface";
const DecodeEnv = async ( const DecodeEnv = async (
extensionlessFilePath: string extensionlessFilePath: string,
): Promise<DecodedEnv> => { ): Promise<DecodedEnv> => {
let dbf: DBFFile | null = null; let dbf: DBFFile | null = null;
try { try {
@@ -32,7 +32,7 @@ const DecodeEnv = async (
//TODO: Several of these fields will fail. Should extend schema to capture them. //TODO: Several of these fields will fail. Should extend schema to capture them.
//"EST_SYSTEM", //"EST_SYSTEM",
"ESTFILE_ID", "ESTFILE_ID",
]) ]),
); );
rawEnvData.ciecaid = rawEnvData.estfile_id; rawEnvData.ciecaid = rawEnvData.estfile_id;
delete 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"; import { DecodedLin, DecodedLinLine } from "./decode-lin.interface";
const DecodeLin = async ( const DecodeLin = async (
extensionlessFilePath: string extensionlessFilePath: string,
): Promise<DecodedLin> => { ): Promise<DecodedLin> => {
let dbf: DBFFile | null = null; let dbf: DBFFile | null = null;
try { try {
@@ -80,7 +80,7 @@ const DecodeLin = async (
"BETT_PCTG", "BETT_PCTG",
"BETT_AMT", "BETT_AMT",
"BETT_TAX", "BETT_TAX",
]) ]),
); );
//Apply line by line adjustments. //Apply line by line adjustments.
singleLineData.op_code_desc = opCodeData[singleLineData.lbr_op]?.desc; 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"; import { DecodedPfh } from "./decode-pfh.interface";
const DecodePfh = async ( const DecodePfh = async (
extensionlessFilePath: string extensionlessFilePath: string,
): Promise<DecodedPfh> => { ): Promise<DecodedPfh> => {
let dbf: DBFFile | null = null; let dbf: DBFFile | null = null;
try { try {
@@ -50,7 +50,7 @@ const DecodePfh = async (
"ADJ_STRDIS", "ADJ_STRDIS",
//"ADJ_BTR_IN", //Remove //"ADJ_BTR_IN", //Remove
"TAX_PREDIS", "TAX_PREDIS",
]) ]),
); );
//Apply business logic transfomrations. //Apply business logic transfomrations.

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -10,7 +10,7 @@ const requestMiddleware: RequestMiddleware = async (request) => {
`%c[Graphql Request]%c${request.operationName}`, `%c[Graphql Request]%c${request.operationName}`,
"color: red", "color: red",
"color: green", "color: green",
request request,
); );
return { return {
@@ -23,7 +23,7 @@ const client: GraphQLClient = new GraphQLClient(
import.meta.env.VITE_GRAPHQL_ENDPOINT, import.meta.env.VITE_GRAPHQL_ENDPOINT,
{ {
requestMiddleware, requestMiddleware,
} },
); );
export async function getTokenFromRenderer(): Promise<string> { export async function getTokenFromRenderer(): Promise<string> {
@@ -35,7 +35,7 @@ export async function getTokenFromRenderer(): Promise<string> {
} catch (error) { } catch (error) {
log.error( log.error(
"Unable to send request to renderer process for token", "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", label: "Log the Store",
click: (): void => { click: (): void => {
log.debug( 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 jobs
{ {
id}} id}}
` `,
) )
.then((data) => { .then((data) => {
log.info("Data from graffle", data); log.info("Data from graffle", data);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,7 +8,7 @@ const Home: React.FC = () => {
<Button <Button
onClick={(): void => { onClick={(): void => {
window.electron.ipcRenderer.send( 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"] = ( const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
errorInfo errorInfo,
) => { ) => {
log.log("Failed:", errorInfo); log.log("Failed:", errorInfo);
}; };

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,5 @@
{ {
"toolbar": { "toolbar": {
"help": "Help" "help": "Help"
} }
} }

View File

@@ -1,20 +1,20 @@
{ {
"translation": { "translation": {
"navigation": { "navigation": {
"home": "Home", "home": "Home",
"settings": "Settings" "settings": "Settings"
}, },
"settings": { "settings": {
"actions": { "actions": {
"addpath": "Add path", "addpath": "Add path",
"startwatcher": "Start Watcher", "startwatcher": "Start Watcher",
"stopwatcher": "Stop Watcher\n" "stopwatcher": "Stop Watcher\n"
}, },
"labels": { "labels": {
"started": "Started", "started": "Started",
"stopped": "Stopped", "stopped": "Stopped",
"watcherstatus": "Watcher Status" "watcherstatus": "Watcher Status"
} }
} }
} }
} }

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

View File

@@ -1,18 +1,20 @@
import { test, expect } from '@playwright/test'; import { test, expect } from "@playwright/test";
test('has title', async ({ page }) => { test("has title", async ({ page }) => {
await page.goto('https://playwright.dev/'); await page.goto("https://playwright.dev/");
// Expect a title "to contain" a substring. // Expect a title "to contain" a substring.
await expect(page).toHaveTitle(/Playwright/); await expect(page).toHaveTitle(/Playwright/);
}); });
test('get started link', async ({ page }) => { test("get started link", async ({ page }) => {
await page.goto('https://playwright.dev/'); await page.goto("https://playwright.dev/");
// Click the get started link. // 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. // 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();
}); });