Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Tests for Delete my account: the sheet, the store action and the Settings row
Duarte Santos342de91feeed
diff --git a/frontend/src/components/DeleteAccount.test.jsx b/frontend/src/components/DeleteAccount.test.jsxnew file mode 100644index 000000000..ccaf0057a--- /dev/null+++ b/frontend/src/components/DeleteAccount.test.jsx@@ -0,0 +1,133 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { DeleteAccountSheet, DeleteAccountRow, deleteAccountError } from './DeleteAccount.jsx'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++/* "Delete my account" on screen: the backup export is offered first, the button does nothing+ until the account's name is typed back, and the server's refusals are said in the UI+ language. The store is a stand-in; what the sheet asks of it and says back is the point. */+const mocks = vi.hoisted(() => {+ const state = { sheets: [] }+ state.toast = vi.fn()+ state.deleteAccount = vi.fn(async () => {})+ state.snapshot = () => ({ user: { id: 'u1', name: 'Mallory' }, deleteAccount: state.deleteAccount })+ return state+})+vi.mock('../store/useStore.js', () => {+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()+ useStore.getState = mocks.snapshot+ return { useStore }+})+vi.mock('../store/useUI.js', () => {+ const snap = () => ({ toast: (...a) => mocks.toast(...a), openSheet: (render, opts) => { mocks.sheets.push({ render, opts }); return {} } })+ const useUI = selector => selector ? selector(snap()) : snap()+ useUI.getState = snap+ return { useUI }+})++const fail = (status, data) => Object.assign(new Error(data?.error || 'HTTP ' + status), { status, data })++const mounted = []+function mount(el) {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ mounted.push({ root, host })+ act(() => root.render(el))+ return host+}+const settle = () => act(() => new Promise(r => setTimeout(r, 0)))+function type(el, value) {+ act(() => {+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)+ el.dispatchEvent(new Event('input', { bubbles: true }))+ })+}+const button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent === text)+const submit = async host => { act(() => { host.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })) }); await settle() }+const alertText = host => host.querySelector('[role="alert"]')?.textContent || null+const field = host => host.querySelector('input[placeholder="Account name"]')++function sheet(props = {}) {+ const p = { close: vi.fn(), exportBackup: vi.fn(), exportBackupZip: vi.fn(), done: vi.fn(), hasMedia: false, ...props }+ return { p, host: mount(<DeleteAccountSheet {...p} />) }+}++beforeEach(() => {+ mocks.sheets.length = 0+ mocks.toast.mockClear()+ mocks.deleteAccount.mockReset()+ mocks.deleteAccount.mockImplementation(async () => {})+})+afterEach(() => {+ for (const { root, host } of mounted.splice(0)) { act(() => root.unmount()); host.remove() }+})++describe('DeleteAccountSheet', () => {+ it('offers the backup export first: the JSON one, or the zip when there are photos and videos', () => {+ const plain = sheet()+ act(() => button(plain.host, 'Export backup (JSON)').click())+ expect(plain.p.exportBackup).toHaveBeenCalledTimes(1)+ expect(button(plain.host, 'Export with photos & videos (.zip)')).toBeUndefined()++ const media = sheet({ hasMedia: true })+ act(() => button(media.host, 'Export with photos & videos (.zip)').click())+ expect(media.p.exportBackupZip).toHaveBeenCalledTimes(1)+ })++ it('does nothing until the account name is typed back', async () => {+ const { host } = sheet()+ expect(host.textContent).toContain('Type Mallory to confirm.')+ expect(button(host, 'Delete forever').disabled).toBe(true)+ type(field(host), 'mallory')+ expect(button(host, 'Delete forever').disabled).toBe(true)+ await submit(host)+ expect(mocks.deleteAccount).not.toHaveBeenCalled()+ type(field(host), 'Mallory ')+ expect(button(host, 'Delete forever').disabled).toBe(false)+ })++ it('deletes with the typed name, then closes, says goodbye and hands over to Settings', async () => {+ const { p, host } = sheet()+ type(field(host), ' Mallory')+ await submit(host)+ expect(mocks.deleteAccount).toHaveBeenCalledWith('Mallory')+ expect(p.close).toHaveBeenCalled()+ expect(p.done).toHaveBeenCalled()+ expect(mocks.toast).toHaveBeenCalledWith('Your account is gone. Thanks for every rep.')+ })++ it('the last admin hears why, and the sheet stays open', async () => {+ mocks.deleteAccount.mockRejectedValue(fail(409, { error: 'the last admin cannot leave while other profiles remain', code: 'last-admin' }))+ const { p, host } = sheet()+ type(field(host), 'Mallory')+ await submit(host)+ expect(alertText(host)).toBe('You’re the only admin here, and other profiles still use this server. Make someone else an admin first.')+ expect(p.close).not.toHaveBeenCalled()+ expect(p.done).not.toHaveBeenCalled()+ expect(button(host, 'Delete forever').disabled).toBe(false) // not stuck on "Deleting…"+ })+})++describe('deleteAccountError', () => {+ it('words each refusal, and anything else as nothing removed', () => {+ expect(deleteAccountError(fail(400, { code: 'confirm-name' }))).toBe('That is not your account name.')+ expect(deleteAccountError(fail(409, { code: 'last-admin' }))).toMatch(/only admin/)+ expect(deleteAccountError(new TypeError('Failed to fetch'))).toBe('Couldn’t delete the account. Nothing was removed.')+ })+})++describe('DeleteAccountRow', () => {+ it('opens the sheet with what Settings hands it', () => {+ const exportBackup = vi.fn()+ const host = mount(<DeleteAccountRow exportBackup={exportBackup} hasMedia={false} />)+ act(() => [...host.querySelectorAll('button')].find(b => b.textContent.includes('Delete my account')).click())+ expect(mocks.sheets).toHaveLength(1)+ const inner = mount(mocks.sheets[0].render(() => {}))+ act(() => button(inner, 'Export backup (JSON)').click())+ expect(exportBackup).toHaveBeenCalled()+ })+})diff --git a/frontend/src/store/useStore.account-delete.test.jsx b/frontend/src/store/useStore.account-delete.test.jsxnew file mode 100644index 000000000..a2f74b2bc--- /dev/null+++ b/frontend/src/store/useStore.account-delete.test.jsx@@ -0,0 +1,67 @@+// @vitest-environment happy-dom++/* Settings → "Delete my account" (useStore deleteAccount): the server removes the profile, then+ this device ends where a sign-out leaves it, with nothing kept aside for an account that no+ longer exists. Refused or unanswered, nothing here changes and the caller hears why. */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))+const { toast, stopRest, abandonWork } = vi.hoisted(() => ({ toast: vi.fn(), stopRest: vi.fn(), abandonWork: vi.fn() }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast, stopRest, abandonWork }) } }))++import { api } from '../lib/api.js'+import { DEF, useStore } from './useStore.js'++const clone = value => JSON.parse(JSON.stringify(value))+const workout = (id, d = '2026-09-01') => ({ id, d, start: 1, entries: [] })+const httpError = (status, data = {}) => Object.assign(new Error(data.error || 'HTTP ' + status), { status, data })+const USER = { id: 'user-1', name: 'One' }+const fresh = { offline: false, pending: false, auth: false, lastError: null, lastSynced: 0, server: null }+const S0 = () => ({ ...clone(DEF), _ts: 100, workouts: [workout('w1')], active: { id: 'run', start: 5, entries: [] } })+// Kept changes of this account and of another one, as a forced sign-out leaves them, keyed by+// server (this page's origin) and account.+const ORIGIN = () => location.origin+const stash = () => ({+ [ORIGIN() + '|' + USER.id]: { server: ORIGIN(), uid: USER.id, name: 'One', at: 1, state: { ...clone(DEF), workouts: [workout('k1')] } },+ [ORIGIN() + '|user-2']: { server: ORIGIN(), uid: 'user-2', name: 'Two', at: 1, state: { ...clone(DEF), workouts: [workout('k2')] } },+})++beforeEach(() => {+ localStorage.clear()+ localStorage.setItem('gym_owner', USER.id)+ localStorage.setItem('gym_stash', JSON.stringify(stash()))+ api.mockReset(); toast.mockReset(); stopRest.mockReset()+ useStore.setState({ S: S0(), user: USER, ready: true, sync: { ...fresh }, config: null })+})+afterEach(() => {+ localStorage.clear()+ useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh }, config: null })+})++describe('deleteAccount', () => {+ it('asks the server with the typed name, then signs this device out and keeps nothing of the account', async () => {+ api.mockResolvedValue({ ok: true })+ await useStore.getState().deleteAccount('One')++ expect(api).toHaveBeenCalledWith('/api/account/delete', { method: 'POST', body: JSON.stringify({ name: 'One' }) })+ const st = useStore.getState()+ expect(st.user).toBeNull()+ expect(st.S.workouts).toEqual([])+ expect(st.S.active).toBeFalsy()+ expect(stopRest).toHaveBeenCalled()+ // Its kept changes have no account to go back to; another account's stay.+ expect(Object.keys(JSON.parse(localStorage.getItem('gym_stash')))).toEqual([ORIGIN() + '|user-2'])+ })++ it('refused by the server: throws, and this device is left exactly as it was', async () => {+ api.mockRejectedValue(httpError(409, { error: 'the last admin cannot leave while other profiles remain', code: 'last-admin' }))+ await expect(useStore.getState().deleteAccount('One')).rejects.toMatchObject({ status: 409, data: { code: 'last-admin' } })++ const st = useStore.getState()+ expect(st.user).toEqual(USER)+ expect(st.S.workouts.map(w => w.id)).toEqual(['w1'])+ expect(st.S.active?.id).toBe('run')+ expect(stopRest).not.toHaveBeenCalled()+ expect(JSON.parse(localStorage.getItem('gym_stash'))).toEqual(stash())+ })+})diff --git a/frontend/src/views/Settings.server-sync.test.jsx b/frontend/src/views/Settings.server-sync.test.jsxindex 56642097c..74decaea5 100644--- a/frontend/src/views/Settings.server-sync.test.jsx+++ b/frontend/src/views/Settings.server-sync.test.jsx@@ -303,3 +303,27 @@ describe('leaving the server', () => {expect(mocks.toast).toHaveBeenLastCalledWith('Couldn’t sign out everywhere. You’re still signed in.')})})++/* "Delete my account" (App Store rule 5.1.1(v)): wherever there is a server account, a paired+ phone or a signed-in browser, and nowhere there is none. Once it is gone, Settings goes home. */+describe('deleting the account', () => {+ it('a paired phone and a signed-in browser both have the row; it goes home once the account is gone', async () => {+ const phone = mount(<Settings page="account" />)+ expect(rowByTitle(phone, 'Delete my account')).toBeTruthy()++ mocks.MOBILE = false+ const page = mount(<Settings page="account" />)+ act(() => rowByTitle(page, 'Delete my account').click())+ const done = mocks.sheets.at(-1).render(() => {}).props.done+ done()+ expect(mocks.navs).toEqual(['/home'])+ })++ it('no account, no row: a phone kept local, and a guest in a browser', async () => {+ mocks.user = null+ mocks.sync = sync('local', { server: null })+ expect(rowByTitle(mount(<Settings page="account" />), 'Delete my account')).toBeUndefined()+ mocks.MOBILE = false+ expect(rowByTitle(mount(<Settings page="account" />), 'Delete my account')).toBeUndefined()+ })+})