Add backend and frontend tests and run them in CI
Build and Publish / Build Yale Access Frontend (pull_request) Successful in 1m17s
Build and Publish / Push Yale Access Frontend Docker Image (pull_request) Skipped
Build and Publish / Build Yale Access Backend (pull_request) Successful in 2m12s
Build and Publish / Push Yale Access Backend Docker Image (pull_request) Skipped

- Backend: xUnit integration tests (auth, rate limiting, people, lock codes,
  validation, error handling) using WebApplicationFactory with a fake lock
- Frontend: Vitest + Nuxt test utils for useApi, the auth middleware,
  LoginForm, UserCodeList and PeopleList
- Run both suites in CI before building
This commit is contained in:
LiamPietralla committed 2026-11-16 12:23:32 +11:00
1 parent a9bef7b50d
commit 4fe6f9d7b5
15 files changed
+968

No files matched your search

+1
View File
@@ -0,0 +1 @@
setups.@nuxt/test-utils="4.4.0"
+66
View File
@@ -0,0 +1,66 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises } from '@vue/test-utils'
import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
import LoginForm from '~/components/LoginForm.vue'
const { api, navigateToMock } = vi.hoisted(() => ({
api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() },
navigateToMock: vi.fn()
}))
mockNuxtImport('useApi', () => () => api)
mockNuxtImport('navigateTo', () => navigateToMock)
describe('LoginForm', () => {
beforeEach(() => {
api.post.mockReset()
navigateToMock.mockReset()
useCookie<boolean>('authenticated').value = false
})
it('disables the login button until a password is entered', async () => {
const wrapper = await mountSuspended(LoginForm)
const button = wrapper.find('button[type="submit"]')
expect(button.attributes('disabled')).toBeDefined()
await wrapper.find('input').setValue('secret')
expect(button.attributes('disabled')).toBeUndefined()
})
it('logs in with the password, sets the cookie and goes home', async () => {
api.post.mockResolvedValue({ success: true, data: true })
const wrapper = await mountSuspended(LoginForm)
await wrapper.find('input').setValue('pa"ss')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(api.post).toHaveBeenCalledWith('/api/Authentication/login', 'pa"ss')
expect(useCookie<boolean>('authenticated').value).toBe(true)
expect(navigateToMock).toHaveBeenCalledWith('/')
})
it('shows the error and stays on the page when the login fails', async () => {
api.post.mockResolvedValue({ success: false, error: 'Incorrect password.' })
const wrapper = await mountSuspended(LoginForm)
await wrapper.find('input').setValue('wrong')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(wrapper.text()).toContain('Incorrect password.')
expect(useCookie<boolean>('authenticated').value).toBe(false)
expect(navigateToMock).not.toHaveBeenCalled()
})
it('can reveal and hide the password', async () => {
const wrapper = await mountSuspended(LoginForm)
const input = wrapper.find('input')
expect(input.attributes('type')).toBe('password')
await wrapper.find('button[aria-label="Show password"]').trigger('click')
expect(input.attributes('type')).toBe('text')
await wrapper.find('button[aria-label="Hide password"]').trigger('click')
expect(input.attributes('type')).toBe('password')
})
})
+101
View File
@@ -0,0 +1,101 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
import PeopleList from '~/components/PeopleList.vue'
import { click, inBody, mountInApp, setInput, settle, submitForm } from './helpers'
const { api } = vi.hoisted(() => ({ api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() } }))
mockNuxtImport('useApi', () => () => api)
const mountList = async () => {
const wrapper = await mountInApp(PeopleList)
await settle()
return wrapper
}
const openAddModal = async (wrapper: Awaited<ReturnType<typeof mountList>>) => {
const add = wrapper.findAll('button').find(b => b.text().includes('Add Person'))
await click(add!.element)
}
const fillAndSubmit = async (name: string, phone: string) => {
const [nameInput, phoneInput] = document.body.querySelectorAll<HTMLInputElement>('#add-person input')
await setInput(nameInput!, name)
await setInput(phoneInput!, phone)
await submitForm(inBody<HTMLFormElement>('#add-person')!)
}
describe('PeopleList', () => {
beforeEach(() => {
api.get.mockReset()
api.post.mockReset()
api.delete.mockReset()
api.get.mockResolvedValue({ success: true, data: [{ id: 1, name: 'Alex', phoneNumber: '+61400000001' }] })
document.body.innerHTML = ''
})
it('lists the people', async () => {
const wrapper = await mountList()
const row = wrapper.find('tbody tr')
expect(row.text()).toContain('Alex')
expect(row.text()).toContain('+61400000001')
})
it('shows an empty state', async () => {
api.get.mockResolvedValue({ success: true, data: [] })
const wrapper = await mountList()
expect(wrapper.text()).toContain('No people yet.')
})
it('requires a name and an international phone number before saving', async () => {
const wrapper = await mountList()
await openAddModal(wrapper)
await fillAndSubmit('', '0400 000 000')
expect(document.body.textContent).toContain('Name is required')
expect(document.body.textContent).toContain('Use international format')
expect(api.post).not.toHaveBeenCalled()
})
it('adds a person and shows them in the table', async () => {
api.post.mockResolvedValue({ success: true, data: { id: 2, name: 'Sam', phoneNumber: '+61400000002' } })
const wrapper = await mountList()
await openAddModal(wrapper)
await fillAndSubmit('Sam', '+61400000002')
expect(api.post).toHaveBeenCalledExactlyOnceWith('/api/People', { id: 0, name: 'Sam', phoneNumber: '+61400000002' })
expect(wrapper.findAll('tbody tr')).toHaveLength(2)
expect(wrapper.text()).toContain('Sam')
})
it('keeps the list unchanged when the API rejects the new person', async () => {
api.post.mockResolvedValue({ success: false, error: 'nope' })
const wrapper = await mountList()
await openAddModal(wrapper)
await fillAndSubmit('Sam', '+61400000002')
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
})
it('deletes a person', async () => {
api.delete.mockResolvedValue({ success: true, data: { id: 1 } })
const wrapper = await mountList()
await click(wrapper.find('button[aria-label="Delete Alex"]').element)
expect(api.delete).toHaveBeenCalledExactlyOnceWith('/api/People/1')
expect(wrapper.text()).not.toContain('+61400000001')
})
it('keeps the person when the delete fails', async () => {
api.delete.mockResolvedValue({ success: false, error: 'Person not found.' })
const wrapper = await mountList()
await click(wrapper.find('button[aria-label="Delete Alex"]').element)
expect(wrapper.text()).toContain('Alex')
})
})
+135
View File
@@ -0,0 +1,135 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
import UserCodeList from '~/components/UserCodeList.vue'
import { UserCodeStatus } from '~/types/yale'
import { click, inBody, mountInApp, setInput, settle, submitForm } from './helpers'
const { api } = vi.hoisted(() => ({ api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() } }))
mockNuxtImport('useApi', () => () => api)
const codes = [
{ id: 4, code: '9999', status: UserCodeStatus.ENABLED, isHome: true },
{ id: 2, code: '2222', status: UserCodeStatus.ENABLED, isHome: false },
{ id: 3, code: '', status: UserCodeStatus.AVAILABLE, isHome: false }
]
const mountList = async () => {
const wrapper = await mountInApp(UserCodeList)
await settle()
return wrapper
}
const rows = (wrapper: Awaited<ReturnType<typeof mountList>>) => wrapper.findAll('tbody tr')
const buttonLabels = (row: { findAll: (s: string) => { attributes: (n: string) => string | undefined }[] }) =>
row.findAll('button').map(b => b.attributes('aria-label'))
describe('UserCodeList', () => {
beforeEach(() => {
api.get.mockReset()
api.post.mockReset()
api.get.mockImplementation(async (path: string) =>
path === '/api/Yale/codes'
? { success: true, data: structuredClone(codes) }
: { success: true, data: [{ id: 1, name: 'Alex', phoneNumber: '+61400000001' }] })
api.post.mockResolvedValue({ success: true, data: true })
document.body.innerHTML = ''
})
it('lists the codes sorted by id with their status', async () => {
const wrapper = await mountList()
const r = rows(wrapper)
expect(r).toHaveLength(3)
expect(r.map(x => x.findAll('td')[0]!.text())).toEqual(['2', '3', '4'])
expect(r[0]!.text()).toContain('Enabled')
expect(r[1]!.text()).toContain('Available')
})
it('only offers show and edit for the home code, and marks it with the home icon', async () => {
const wrapper = await mountList()
const home = rows(wrapper)[2]!
expect(buttonLabels(home)).toEqual(['Show code', 'Edit code'])
expect(home.find('[aria-label="Home code"]').exists()).toBe(true)
})
it('disables show, send and delete for an available (unset) code', async () => {
const wrapper = await mountList()
const available = rows(wrapper)[1]!
for (const label of ['Show code', 'Send code', 'Delete code']) {
expect(available.find(`button[aria-label="${label}"]`).attributes('disabled')).toBeDefined()
}
expect(available.find('button[aria-label="Edit code"]').attributes('disabled')).toBeUndefined()
})
it('shows the code in a modal', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[0]!.find('button[aria-label="Show code"]').element)
expect(document.body.textContent).toContain('User Code #2')
expect(document.body.textContent).toContain('2222')
})
it('rejects a code that is not 4-6 digits without calling the API', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[0]!.find('button[aria-label="Edit code"]').element)
await setInput(inBody<HTMLInputElement>('input')!, '12')
await submitForm(inBody<HTMLFormElement>('#edit-code')!)
expect(document.body.textContent).toContain('Code must be 4, 5 or 6 digits long')
expect(api.post).not.toHaveBeenCalled()
})
it('updates a code through the API and reflects it in the table', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[1]!.find('button[aria-label="Edit code"]').element) // available code #3
await setInput(inBody<HTMLInputElement>('input')!, '123456')
await submitForm(inBody<HTMLFormElement>('#edit-code')!)
expect(api.post).toHaveBeenCalledExactlyOnceWith('/api/Yale/code/3', '123456')
expect(rows(wrapper)[1]!.text()).toContain('Enabled')
})
it('warns before editing the home code', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[2]!.find('button[aria-label="Edit code"]').element)
expect(document.body.textContent).toContain('You are about to edit the home code')
})
it('does not change the table when the API rejects the update', async () => {
api.post.mockResolvedValue({ success: false, error: 'An error occurred setting the code.' })
const wrapper = await mountList()
await click(rows(wrapper)[1]!.find('button[aria-label="Edit code"]').element)
await setInput(inBody<HTMLInputElement>('input')!, '4321')
await submitForm(inBody<HTMLFormElement>('#edit-code')!)
expect(rows(wrapper)[1]!.text()).toContain('Available')
})
it('deletes a code after confirmation and marks it available', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[0]!.find('button[aria-label="Delete code"]').element) // code #2
expect(document.body.textContent).toContain('Are you sure you want to delete this code?')
expect(api.post).not.toHaveBeenCalled()
const confirm = [...document.body.querySelectorAll('button')].find(b => b.textContent?.trim() === 'Delete Code')
await click(confirm ?? null)
expect(api.post).toHaveBeenCalledExactlyOnceWith('/api/Yale/code/2/status')
expect(rows(wrapper)[0]!.text()).toContain('Available')
})
it('keeps the send button disabled until a person is chosen', async () => {
const wrapper = await mountList()
await click(rows(wrapper)[0]!.find('button[aria-label="Send code"]').element)
const send = [...document.body.querySelectorAll('button')].find(b => b.textContent?.trim() === 'Send Code')
expect(send?.hasAttribute('disabled')).toBe(true)
})
})
@@ -0,0 +1,47 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
import middleware from '~/middleware/authentication.global'
// Returning false aborts the navigation. (Returning a path would make the real router follow it, and
// since this mock also applies to the app's own startup navigation, that could redirect forever.)
const { navigateToMock } = vi.hoisted(() => ({ navigateToMock: vi.fn(() => false) }))
mockNuxtImport('navigateTo', () => navigateToMock)
// The middleware only reads `to.path`
const run = (path: string) => (middleware as (to: unknown, from: unknown) => unknown)({ path }, { path: '/' })
describe('authentication middleware', () => {
describe('when logged out', () => {
beforeEach(() => {
useCookie<boolean>('authenticated').value = false
navigateToMock.mockClear()
})
it.each(['/', '/people'])('redirects %s to the login page', (path) => {
run(path)
expect(navigateToMock).toHaveBeenCalledExactlyOnceWith('/login')
})
it.each(['/login', '/health'])('allows anonymous access to %s', (path) => {
expect(run(path)).toBeUndefined()
expect(navigateToMock).not.toHaveBeenCalled()
})
})
describe('when logged in', () => {
beforeEach(() => {
useCookie<boolean>('authenticated').value = true
navigateToMock.mockClear()
})
it.each(['/', '/people', '/health'])('allows %s', (path) => {
expect(run(path)).toBeUndefined()
expect(navigateToMock).not.toHaveBeenCalled()
})
it('skips the login page', () => {
run('/login')
expect(navigateToMock).toHaveBeenCalledExactlyOnceWith('/')
})
})
})
+37
View File
@@ -0,0 +1,37 @@
import { expect } from 'vitest'
import { defineComponent, h, nextTick, type Component } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { UApp } from '#components'
/** Mounts a component inside <UApp>, which modals and toasts need. */
export const mountInApp = (component: Component) =>
mountSuspended(defineComponent({ render: () => h(UApp, null, { default: () => h(component) }) }))
/** Lets promises, reactivity and (async) form validation settle. */
export const settle = async () => {
for (let i = 0; i < 4; i++) {
await flushPromises()
await nextTick()
}
}
/** Modals render in a portal, so query the whole document. */
export const inBody = <T extends Element = HTMLElement>(selector: string) => document.body.querySelector<T>(selector)
export const setInput = async (input: HTMLInputElement, value: string) => {
input.value = value
input.dispatchEvent(new Event('input', { bubbles: true }))
await settle()
}
export const submitForm = async (form: HTMLFormElement) => {
form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
await settle()
}
export const click = async (el: Element | null) => {
expect(el, 'element to click').not.toBeNull()
;(el as HTMLElement).click()
await settle()
}
+98
View File
@@ -0,0 +1,98 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mockNuxtImport, registerEndpoint } from '@nuxt/test-utils/runtime'
import { createError, defineEventHandler, getHeader, readBody, setResponseStatus } from 'h3'
import { useApi } from '~/composables/useApi'
const { navigateToMock } = vi.hoisted(() => ({ navigateToMock: vi.fn() }))
mockNuxtImport('navigateTo', () => navigateToMock)
// Each test registers its own endpoint, with an empty base URL (see vitest.config.ts) so requests hit it directly
const respond = (path: string, status: number, body: unknown, method: 'GET' | 'POST' | 'DELETE' = 'GET') =>
registerEndpoint(path, {
method,
handler: defineEventHandler((event) => {
setResponseStatus(event, status)
return body
})
})
describe('useApi', () => {
beforeEach(() => {
navigateToMock.mockReset()
useCookie<boolean>('authenticated').value = true
})
it('returns the API response on success', async () => {
respond('/api/test/ok', 200, { success: true, data: [1, 2] })
expect(await useApi().get<number[]>('/api/test/ok')).toEqual({ success: true, data: [1, 2] })
})
it('JSON-encodes bare string bodies so quotes and backslashes survive', async () => {
const password = 'pa"ss\\word'
let received: unknown
let contentType: string | undefined
registerEndpoint('/api/test/echo', {
method: 'POST',
handler: defineEventHandler(async (event) => {
contentType = getHeader(event, 'content-type')
received = await readBody(event)
return { success: true }
})
})
await useApi().post('/api/test/echo', password)
expect(contentType).toContain('application/json')
expect(received).toBe(password)
})
it('sends DELETE requests', async () => {
respond('/api/test/delete', 200, { success: true, data: { id: 3 } }, 'DELETE')
expect((await useApi().delete('/api/test/delete')).success).toBe(true)
})
it('passes through the API error message for failed requests', async () => {
respond('/api/test/bad', 400, { success: false, error: 'The code must be numeric.' }, 'POST')
const result = await useApi().post('/api/test/bad', 'abcd')
expect(result).toEqual({ success: false, error: 'The code must be numeric.' })
expect(navigateToMock).not.toHaveBeenCalled()
})
it('does not treat a wrong-password 401 as an expired session', async () => {
respond('/api/test/login', 401, { success: false, error: 'Incorrect password.' }, 'POST')
const result = await useApi().post('/api/test/login', 'nope')
expect(result.error).toBe('Incorrect password.')
expect(navigateToMock).not.toHaveBeenCalled()
expect(useCookie<boolean>('authenticated').value).toBe(true)
})
it('sends the user to the login page when the session has expired (empty 401)', async () => {
registerEndpoint('/api/test/expired', () => {
throw createError({ statusCode: 401, data: undefined })
})
const result = await useApi().get('/api/test/expired')
expect(result.success).toBe(false)
expect(result.error).toMatch(/session has expired/i)
expect(navigateToMock).toHaveBeenCalledWith('/login')
expect(useCookie<boolean>('authenticated').value).toBe(false)
})
it('surfaces rate limiting (429) messages', async () => {
respond('/api/test/limited', 429, { success: false, error: 'Too many login attempts.' }, 'POST')
expect((await useApi().post('/api/test/limited', 'x')).error).toBe('Too many login attempts.')
})
it('falls back to a generic message when the server cannot be reached', async () => {
// Nothing is registered at this path and the request is aborted by the network layer
const result = await useApi().get('http://127.0.0.1:1/unreachable')
expect(result).toEqual({ success: false, error: 'Unable to reach the server.' })
expect(navigateToMock).not.toHaveBeenCalled()
})
})
+20
View File
@@ -0,0 +1,20 @@
import { defineVitestConfig } from '@nuxt/test-utils/config'
export default defineVitestConfig({
test: {
environment: 'nuxt',
include: ['test/**/*.test.ts'],
// Booting the Nuxt environment can be slow on a cold start (and in CI)
hookTimeout: 60_000,
testTimeout: 30_000,
environmentOptions: {
nuxt: {
domEnvironment: 'happy-dom',
// Empty base URL so $fetch calls hit endpoints registered with registerEndpoint()
overrides: {
runtimeConfig: { public: { apiBaseUrl: '' } }
}
}
}
}
})