Skip to content

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.

10.4 KB
Raw Blame
// @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 Settings from './Settings.jsx'

globalThis.IS_REACT_ACT_ENVIRONMENT = true

// #200: the Health Connect card. Only on the Android app, only where Health Connect is there or
// can be installed, off until switched on, and turning it off asks what happens to what was
// already written. lib/health-sync.js is mocked; its own tests cover the writing.
const mocks = vi.hoisted(() => {
  const state = { S: null, MOBILE: true, android: true, status: { status: 'available', granted: false }, health: { on: false, written: {}, error: null } }
  state.snapshot = () => ({
    S: state.S, user: null, update: vi.fn(),
    replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
    signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
  })
  state.enableHealth = vi.fn(async () => { state.health = { ...state.health, on: true }; return { ok: true, health: state.health } })
  state.disableHealth = vi.fn(async ({ removeWritten }) => { state.health = { ...state.health, on: false, written: removeWritten ? {} : state.health.written }; return state.health })
  state.openHealthConnect = vi.fn(async () => {})
  state.readGrant = true
  state.enableRead = vi.fn(async kind => {
    if (!state.readGrant) return { ok: false, reason: 'denied' }
    state.health = { ...state.health, [kind === 'hr' ? 'readHr' : 'readWeight']: true }
    return { ok: true, health: state.health }
  })
  state.disableRead = vi.fn(async kind => { state.health = { ...state.health, [kind === 'hr' ? 'readHr' : 'readWeight']: false }; return state.health })
  state.menuSheet = vi.fn()
  state.toast = vi.fn()
  return state
})
vi.mock('../store/useStore.js', () => {
  const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
  useStore.getState = mocks.snapshot
  return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
})
vi.mock('../store/useUI.js', () => {
  const snap = () => ({ toast: mocks.toast, openSheet: vi.fn() })
  const useUI = selector => selector ? selector(snap()) : snap()
  useUI.getState = snap
  return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({ api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false }))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({
  get MOBILE() { return mocks.MOBILE },
  isAndroid: () => Promise.resolve(mocks.android),
  shareExport: vi.fn(), syncReminder: vi.fn(),
}))
vi.mock('../lib/update.js', () => ({ checkForUpdate: () => Promise.resolve({ hasUpdate: false }), downloadAndInstall: vi.fn() }))
vi.mock('../lib/health-sync.js', () => ({
  healthStatus: () => Promise.resolve(mocks.status),
  loadHealth: () => Promise.resolve(mocks.health),
  enableHealth: (...a) => mocks.enableHealth(...a),
  disableHealth: (...a) => mocks.disableHealth(...a),
  openHealthConnect: (...a) => mocks.openHealthConnect(...a),
  onHealthChange: () => () => {},
  enableRead: (...a) => mocks.enableRead(...a),
  disableRead: (...a) => mocks.disableRead(...a),
}))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
  starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
  importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: (...a) => mocks.menuSheet(...a),
}))

globalThis.__APP_VERSION__ ??= 'test'

let host, root
beforeEach(() => {
  mocks.S = { unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none', gifSize: 'full', workouts: [], routines: [], exWeights: {} }
  mocks.MOBILE = true
  mocks.android = true
  mocks.status = { status: 'available', granted: false }
  mocks.health = { on: false, written: {}, error: null }
  mocks.readGrant = true
  for (const k of ['enableHealth', 'disableHealth', 'openHealthConnect', 'menuSheet', 'toast', 'enableRead', 'disableRead']) mocks[k].mockClear()
  host = document.createElement('div')
  document.body.appendChild(host)
  root = createRoot(host)
})
afterEach(() => {
  act(() => root.unmount())
  host.remove()
})

const mount = async () => {
  await act(async () => { root.render(<Settings page="data" />) })
  await act(async () => { await Promise.resolve(); await Promise.resolve() })
}
const row = text => [...host.querySelectorAll('.lrow')].find(r => r.textContent.includes(text))
const writeSwitch = () => row('Write to Health Connect')?.querySelector('[role="switch"]')

describe('Settings — Health Connect', () => {
  it('is not there on the web build, on iOS, or on a phone without Health Connect', async () => {
    mocks.MOBILE = false
    await mount()
    expect(row('Health Connect')).toBeUndefined()

    mocks.MOBILE = true
    mocks.android = false
    await mount()
    expect(row('Health Connect')).toBeUndefined()

    mocks.android = true
    mocks.status = { status: 'unsupported', granted: false }
    await mount()
    expect(row('Health Connect')).toBeUndefined()
  })

  it('starts off, and turning it on goes through enableHealth', async () => {
    await mount()
    expect(writeSwitch().getAttribute('aria-checked')).toBe('false')
    expect(row('Open Health Connect')).toBeUndefined()
    await act(async () => { writeSwitch().click() })
    expect(mocks.enableHealth).toHaveBeenCalledTimes(1)
    expect(writeSwitch().getAttribute('aria-checked')).toBe('true')
    expect(row('Open Health Connect')).toBeTruthy()
  })

  it('turning it off asks whether to keep or remove what was written', async () => {
    mocks.health = { on: true, written: { 'opengym-w-w1': { k: 'session', h: 'x' } }, error: null }
    await mount()
    act(() => { writeSwitch().click() })
    expect(mocks.disableHealth).not.toHaveBeenCalled()
    const items = mocks.menuSheet.mock.calls[0][0].items
    await act(async () => { await items[1].onClick() })
    expect(mocks.disableHealth).toHaveBeenCalledWith({ removeWritten: true })
    expect(writeSwitch().getAttribute('aria-checked')).toBe('false')
  })

  it('offers to grant the permission again when Health Connect refused it', async () => {
    mocks.health = { on: true, written: {}, error: 'permission' }
    await mount()
    await act(async () => { row('Permission withdrawn').click() })
    expect(mocks.enableHealth).toHaveBeenCalledTimes(1)
  })

  it('points to installing Health Connect where it is an app of its own', async () => {
    mocks.status = { status: 'missing', granted: false }
    await mount()
    expect(writeSwitch()).toBeUndefined()
    await act(async () => { row('Install Health Connect').click() })
    expect(mocks.openHealthConnect).toHaveBeenCalledTimes(1)
  })
})

// The iPhone app: the same card for Apple Health, the switch the Apple Watch app goes by too.
describe('Settings — Apple Health', () => {
  beforeEach(() => { mocks.android = false; mocks.status = { status: 'available', granted: false, platform: 'ios' } })
  const appleSwitch = () => row('Write to Apple Health')?.querySelector('[role="switch"]')

  it('is there on the iPhone app, in Apple Health words', async () => {
    await mount()
    expect(appleSwitch().getAttribute('aria-checked')).toBe('false')
    expect(row('Health Connect')).toBeUndefined()
    await act(async () => { appleSwitch().click() })
    expect(mocks.enableHealth).toHaveBeenCalledTimes(1)
    expect(mocks.toast).toHaveBeenCalledWith('Writing to Apple Health')
    expect(row('Open Apple Health')).toBeTruthy()
  })

  it('asks in Apple Health words before turning it off', async () => {
    mocks.health = { on: true, written: {}, error: null }
    await mount()
    act(() => { appleSwitch().click() })
    expect(mocks.menuSheet.mock.calls[0][0].title).toBe('Stop writing to Apple Health?')
  })

  it('is not there on an iPhone without Apple Health', async () => {
    mocks.status = { status: 'unsupported', granted: false, platform: 'ios' }
    await mount()
    expect(appleSwitch()).toBeUndefined()
  })
})

// v1.4.3: reading heart rate and weigh-ins back, each its own switch, independent of writing.
describe('Settings — reading back', () => {
  const sw = text => row(text)?.querySelector('[role="switch"]')

  it('offers both reads, off, next to the write switch on Android and iPhone', async () => {
    await mount()
    expect(sw('Heart rate from your watch').getAttribute('aria-checked')).toBe('false')
    expect(sw('Weigh-ins from other apps').getAttribute('aria-checked')).toBe('false')
    mocks.android = false
    mocks.status = { status: 'available', granted: false, platform: 'ios' }
    await mount()
    expect(sw('Heart rate from your watch')).toBeTruthy()
  })

  it('turns one on without the write switch and without the other read', async () => {
    await mount()
    await act(async () => { sw('Heart rate from your watch').click() })
    expect(mocks.enableRead).toHaveBeenCalledWith('hr', expect.any(Function))
    expect(sw('Heart rate from your watch').getAttribute('aria-checked')).toBe('true')
    expect(sw('Weigh-ins from other apps').getAttribute('aria-checked')).toBe('false')
    expect(writeSwitch().getAttribute('aria-checked')).toBe('false')
    expect(mocks.enableHealth).not.toHaveBeenCalled()
    expect(host.textContent).toContain('openGym reads only while it is open')
    expect(row('Open Health Connect')).toBeTruthy()
  })

  it('says so when the permission was not granted', async () => {
    mocks.readGrant = false
    await mount()
    await act(async () => { sw('Weigh-ins from other apps').click() })
    expect(mocks.toast).toHaveBeenCalledWith('Health Connect permission not granted')
    expect(sw('Weigh-ins from other apps').getAttribute('aria-checked')).toBe('false')
  })

  it('turns off without asking, and offers to ask again after a withdrawn permission', async () => {
    mocks.health = { on: false, written: {}, error: null, readWeight: true, readError: 'permission' }
    await mount()
    await act(async () => { row('Permission withdrawn').click() })
    expect(mocks.enableRead).toHaveBeenCalledWith('weight', expect.any(Function))
    await act(async () => { sw('Weigh-ins from other apps').click() })
    expect(mocks.disableRead).toHaveBeenCalledWith('weight')
    expect(mocks.menuSheet).not.toHaveBeenCalled()
  })
})