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

+7
View File
@@ -33,6 +33,9 @@ jobs:
- name: Build - name: Build
run: dotnet build --configuration Release --no-restore run: dotnet build --configuration Release --no-restore
- name: Test
run: dotnet test ../backend.Tests --configuration Release
publish-backend: publish-backend:
name: Push Yale Access Backend Docker Image name: Push Yale Access Backend Docker Image
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -83,6 +86,10 @@ jobs:
working-directory: packages/frontend working-directory: packages/frontend
runtime: node@22 runtime: node@22
- name: Test
working-directory: ./packages/frontend
run: pnpm run test
- name: Build - name: Build
working-directory: ./packages/frontend working-directory: ./packages/frontend
run: pnpm run build run: pnpm run build
+2
View File
@@ -0,0 +1,2 @@
bin/
obj/
@@ -0,0 +1,101 @@
using System.Net;
using System.Net.Http.Json;
namespace YaleAccess.Tests;
public class AuthenticationTests
{
[Fact]
public async Task Protected_endpoints_return_401_without_a_login()
{
using var app = new TestApp();
var client = app.CreateClient();
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/People")).StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/Yale/codes")).StatusCode);
}
[Fact]
public async Task Health_endpoint_is_anonymous()
{
using var app = new TestApp();
var response = await app.CreateClient().GetAsync("/api/Health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task Wrong_password_is_rejected_and_sets_no_cookie()
{
using var app = new TestApp();
var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", "wrong");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.False(response.Headers.Contains("Set-Cookie"));
var body = await response.ReadApiAsync();
Assert.False(body.GetProperty("success").GetBoolean());
Assert.Equal("Incorrect password.", body.GetProperty("error").GetString());
}
[Fact]
public async Task Correct_password_sets_a_strict_httponly_cookie_and_grants_access()
{
using var app = new TestApp();
var client = app.CreateClient();
var login = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password);
Assert.Equal(HttpStatusCode.OK, login.StatusCode);
var cookie = Assert.Single(login.Headers.GetValues("Set-Cookie"));
Assert.Contains("samesite=strict", cookie, StringComparison.OrdinalIgnoreCase);
Assert.Contains("httponly", cookie, StringComparison.OrdinalIgnoreCase);
Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/api/People")).StatusCode);
}
[Fact]
public async Task Passwords_containing_quotes_and_backslashes_work()
{
const string password = "pa\"ss\\word";
using var app = new TestApp(password);
var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", password);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task Logout_ends_the_session()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
Assert.Equal(HttpStatusCode.OK, (await client.PostAsync("/api/Authentication/logout", null)).StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/People")).StatusCode);
}
[Fact]
public async Task Login_is_refused_when_no_password_is_configured()
{
using var app = new TestApp(password: "");
var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", "");
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}
[Fact]
public async Task Login_attempts_are_rate_limited()
{
using var app = new TestApp();
var client = app.CreateClient();
for (int i = 0; i < 5; i++)
{
var attempt = await client.PostAsJsonAsync("/api/Authentication/login", "wrong");
Assert.Equal(HttpStatusCode.Unauthorized, attempt.StatusCode);
}
// Even the right password is blocked once the limit is hit
var limited = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password);
Assert.Equal(HttpStatusCode.TooManyRequests, limited.StatusCode);
var body = await limited.ReadApiAsync();
Assert.False(body.GetProperty("success").GetBoolean());
Assert.Contains("Too many", body.GetProperty("error").GetString());
}
}
+77
View File
@@ -0,0 +1,77 @@
using System.Net;
using System.Net.Http.Json;
namespace YaleAccess.Tests;
public class PeopleTests
{
[Fact]
public async Task Create_list_and_delete_a_person()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var created = await client.PostAsJsonAsync("/api/People", new { name = " Alex ", phoneNumber = "+61400000001" });
Assert.Equal(HttpStatusCode.OK, created.StatusCode);
var person = (await created.ReadApiAsync()).GetProperty("data");
Assert.Equal("Alex", person.GetProperty("name").GetString()); // trimmed
int id = person.GetProperty("id").GetInt32();
var list = (await (await client.GetAsync("/api/People")).ReadApiAsync()).GetProperty("data");
Assert.Single(list.EnumerateArray());
Assert.Equal(HttpStatusCode.OK, (await client.DeleteAsync($"/api/People/{id}")).StatusCode);
list = (await (await client.GetAsync("/api/People")).ReadApiAsync()).GetProperty("data");
Assert.Empty(list.EnumerateArray());
}
[Theory]
[InlineData("0400000000")] // no country code
[InlineData("+61 400 000 001")] // spaces
[InlineData("+0123456789")] // leading zero after +
[InlineData("+12345")] // too short
[InlineData("")]
public async Task Invalid_phone_numbers_are_rejected(string phone)
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/People", new { name = "Alex", phoneNumber = phone });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Contains("international format", (await response.ReadApiAsync()).GetProperty("error").GetString());
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public async Task A_name_is_required(string name)
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/People", new { name, phoneNumber = "+61400000001" });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Names_over_100_characters_are_rejected()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/People", new { name = new string('a', 101), phoneNumber = "+61400000001" });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Deleting_a_missing_person_returns_404()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.DeleteAsync("/api/People/9999");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal("Person not found.", (await response.ReadApiAsync()).GetProperty("error").GetString());
}
}
+107
View File
@@ -0,0 +1,107 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http.Json;
using System.Text.Json;
using YaleAccess.Models;
using YaleAccess.Services.Interfaces;
namespace YaleAccess.Tests;
public static class TestConstants
{
public const string Password = "test-password";
public const int HomeCode = 1;
}
/// <summary>
/// In-memory stand-in for the Z-Wave lock.
/// </summary>
public class FakeYaleAccessor : IYaleAccessor
{
public Dictionary<int, YaleUserCode> Codes { get; } = new()
{
[1] = new() { Id = 1, Code = "1111", Status = UserCodeStatus.ENABLED },
[2] = new() { Id = 2, Code = "2222", Status = UserCodeStatus.ENABLED },
[3] = new() { Id = 3, Code = "", Status = UserCodeStatus.AVAILABLE },
};
public bool FailWrites { get; set; }
public bool ThrowOnRead { get; set; }
public Task<YaleUserCode> GetCodeInformationAsync(int userCodeId)
{
if (ThrowOnRead) throw new InvalidOperationException("Lock unavailable");
var c = Codes[userCodeId];
return Task.FromResult(new YaleUserCode { Id = c.Id, Code = c.Code, Status = c.Status });
}
public Task<bool> SetUserCode(int userCodeId, string code)
{
if (FailWrites) return Task.FromResult(false);
Codes[userCodeId].Code = code;
Codes[userCodeId].Status = UserCodeStatus.ENABLED;
return Task.FromResult(true);
}
public Task<bool> SetCodeAsAvailable(int userCode)
{
if (FailWrites) return Task.FromResult(false);
Codes[userCode].Code = "";
Codes[userCode].Status = UserCodeStatus.AVAILABLE;
return Task.FromResult(true);
}
}
/// <summary>
/// Boots the real app with a throwaway SQLite database and a fake lock.
/// Use a fresh instance per test: the login rate limiter is per app instance.
/// </summary>
public class TestApp : WebApplicationFactory<Program>
{
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"yale-test-{Guid.NewGuid():N}.db");
private readonly string _password;
public FakeYaleAccessor Lock { get; } = new();
public TestApp(string password = TestConstants.Password) => _password = password;
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Development keeps the auth cookie non-Secure, so it works over the test server's plain HTTP
builder.UseEnvironment("Development");
builder.UseSetting("UseMockDevelopmentMode", "false");
builder.UseSetting("ConnectionStrings:YaleContext", $"Data Source={_dbPath}");
builder.UseSetting("Authentication:Password", _password);
builder.UseSetting("Codes:Home", TestConstants.HomeCode.ToString());
builder.UseSetting("Codes:GuestCodeRangeStart", "2");
builder.UseSetting("Codes:GuestCodeRangeCount", "2");
builder.ConfigureTestServices(services =>
{
services.AddSingleton<IYaleAccessor>(Lock);
});
}
public async Task<HttpClient> LoggedInClientAsync()
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password);
response.EnsureSuccessStatusCode();
return client;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
try { File.Delete(_dbPath); } catch { /* best effort */ }
}
}
public static class HttpExtensions
{
public static async Task<JsonElement> ReadApiAsync(this HttpResponseMessage response)
=> await response.Content.ReadFromJsonAsync<JsonElement>();
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\backend\YaleAccess.csproj" />
</ItemGroup>
</Project>
+143
View File
@@ -0,0 +1,143 @@
using System.Net;
using System.Net.Http.Json;
using YaleAccess.Models;
using YaleAccess.Services;
namespace YaleAccess.Tests;
public class YaleCodeValidationTests
{
[Theory]
[InlineData("1234")]
[InlineData("12345")]
[InlineData("123456")]
[InlineData("0000")]
public void Valid_codes_pass(string code) => Assert.Equal(string.Empty, YaleAccessor.ValidateCode(code));
[Theory]
[InlineData("")]
[InlineData("123")]
[InlineData("1234567")]
public void Wrong_length_is_rejected(string code) => Assert.NotEqual(string.Empty, YaleAccessor.ValidateCode(code));
[Theory]
[InlineData("12a4")]
[InlineData("+123")]
[InlineData("-123")]
[InlineData(" 123")]
[InlineData("12.4")]
[InlineData("١٢٣٤")] // Arabic-Indic digits, not ASCII
public void Non_digit_codes_are_rejected(string code) => Assert.Equal("The code must be numeric.", YaleAccessor.ValidateCode(code));
[Fact]
public void The_home_code_cannot_be_cleared()
{
Assert.NotEqual(string.Empty, YaleAccessor.ValidateClearCode(1, 1));
Assert.Equal(string.Empty, YaleAccessor.ValidateClearCode(2, 1));
}
}
public class YaleEndpointTests
{
[Fact]
public async Task Codes_list_includes_guest_codes_and_flags_the_home_code()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var data = (await (await client.GetAsync("/api/Yale/codes")).ReadApiAsync()).GetProperty("data");
var codes = data.EnumerateArray().ToList();
Assert.Equal(3, codes.Count); // 2 guest codes + home
Assert.Equal(new[] { 1 }, codes.Where(c => c.GetProperty("isHome").GetBoolean()).Select(c => c.GetProperty("id").GetInt32()));
}
[Fact]
public async Task Setting_a_valid_code_updates_the_lock()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/3", "4321");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("4321", app.Lock.Codes[3].Code);
Assert.Equal(UserCodeStatus.ENABLED, app.Lock.Codes[3].Status);
}
[Theory]
[InlineData("12a4")]
[InlineData("+123")]
[InlineData("12")]
public async Task Invalid_codes_are_rejected_without_touching_the_lock(string code)
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/2", code);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("2222", app.Lock.Codes[2].Code);
}
[Fact]
public async Task A_failed_lock_write_returns_502()
{
using var app = new TestApp();
app.Lock.FailWrites = true;
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/2", "4321");
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
}
[Fact]
public async Task Clearing_a_guest_code_makes_it_available()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsync("/api/Yale/code/2/status", null);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(UserCodeStatus.AVAILABLE, app.Lock.Codes[2].Status);
}
[Fact]
public async Task The_home_code_cannot_be_cleared_via_the_api()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsync("/api/Yale/code/1/status", null);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(UserCodeStatus.ENABLED, app.Lock.Codes[1].Status);
}
[Fact]
public async Task Sending_an_unset_code_is_rejected()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/3/send", "+61400000001");
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Unexpected_errors_become_a_json_500_without_leaking_details()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
app.Lock.ThrowOnRead = true;
var response = await client.GetAsync("/api/Yale/codes");
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
var body = await response.ReadApiAsync();
Assert.False(body.GetProperty("success").GetBoolean());
Assert.Equal("An unexpected error occurred.", body.GetProperty("error").GetString());
}
}
+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: '' } }
}
}
}
}
})