Files
jobtrackingapp/job-tracker-ui/src/interview-prep.test.tsx
T

801 lines
50 KiB
TypeScript

import React from "react";
import "@testing-library/jest-dom";
import { act, fireEvent, render as rtlRender, screen, waitFor, within } from "@testing-library/react";
import { ApplicationFollowUp, ApplicationInterviewPrep } from "./components/InterviewPrep";
import { api } from "./api";
import { I18nProvider } from "./i18n/I18nProvider";
import { ConfirmProvider } from "./confirm";
import { translations } from './i18n/translations';
const render = (ui: React.ReactElement) => rtlRender(<I18nProvider><ConfirmProvider>{ui}</ConfirmProvider></I18nProvider>);
jest.mock("./api", () => ({
api: {
get: jest.fn(),
post: jest.fn(),
patch: jest.fn(),
put: jest.fn(),
delete: jest.fn(),
interceptors: { request: { use: jest.fn() }, response: { use: jest.fn() } },
},
getApiErrorMessage: (_e: any, fallback?: string) => fallback || "Request failed.",
}));
const mockedApi = api as jest.Mocked<typeof api>;
const board = {
groups: [
{
category: "company-research",
label: "Company research",
items: [
{ id: 1, category: "company-research", title: "Funding history", content: "Series B in 2025.", source: "user", isPrepared: true, sortOrder: 1, updatedAtUtc: "2026-07-19T10:00:00Z" },
],
},
{
category: "behavioural",
label: "Behavioural questions",
items: [
{ id: 2, category: "behavioural", title: "Tell me about a conflict", content: null, source: "ai", isPrepared: false, sortOrder: 2, updatedAtUtc: "2026-07-19T10:00:00Z" },
],
},
],
total: 2,
prepared: 1,
percent: 50,
isInterviewStage: true,
aiSuggestionCount: 1,
};
const followUp = { followUpAt: "2026-07-26T00:00:00", nextAction: "Chase recruiter", responseReceived: false, openFollowUpTasks: 1 };
function routeGet(overrides: Record<string, any> = {}) {
mockedApi.get.mockImplementation((url: string) => {
if (url.endsWith("/follow-up")) return Promise.resolve({ data: overrides.followUp ?? followUp } as any);
if (url.endsWith("/cv")) return Promise.resolve({ data: overrides.cv ?? { attachedVariantId: 3, attachedVariantName: "Backend CV" } } as any);
return Promise.resolve({ data: overrides.board ?? board } as any);
});
}
beforeEach(() => {
jest.clearAllMocks();
window.localStorage.setItem("uiLanguage", "en");
});
function deferredRead() {
let resolve!: (value: any) => void;
let reject!: (reason: unknown) => void;
const promise = new Promise<any>((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
test.each((['en', 'nb'] as const).flatMap(language => (['ready', 'add', 'delete', 'save'] as const).map(operation => [language, operation] as const)))('same-application %s %s refresh keeps a sibling answer mounted until explicit discard', async (language, operation) => {
localStorage.setItem('uiLanguage', language);
const copy = translations[language];
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
const refresh = deferredRead(); let reads = 0;
mockedApi.get.mockImplementation((url: string) => url.endsWith('/interview-prep') && ++reads > 1 ? refresh.promise : read(url));
mockedApi.patch.mockReset().mockResolvedValue({ data: board.groups[0].items[0] } as any);
mockedApi.post.mockReset().mockResolvedValue({ data: board.groups[0].items[0] } as any);
mockedApi.delete.mockReset().mockResolvedValue({ data: null } as any);
render(<ApplicationInterviewPrep jobId={7} />);
const name = copy.interviewPrepAnswerFor.replace('{title}', 'Tell me about a conflict');
const answer = await screen.findByRole('textbox', { name });
fireEvent.change(answer, { target: { value: 'My unsaved sibling answer Øresund' } });
if (operation === 'ready') fireEvent.click(screen.getByRole('checkbox', { name: copy.interviewPrepReadyLabel.replace('{title}', 'Funding history') }));
if (operation === 'add') {
fireEvent.change(screen.getByLabelText(copy.interviewPrepAddLabel), { target: { value: 'New prep item' } });
fireEvent.click(screen.getByRole('button', { name: copy.interviewPrepAdd }));
}
if (operation === 'delete') {
fireEvent.click(screen.getByRole('button', { name: copy.interviewPrepDeleteLabel.replace('{title}', 'Funding history') }));
fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: copy.interviewPrepDelete }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
}
if (operation === 'save') {
fireEvent.change(screen.getByRole('textbox', { name: copy.interviewPrepAnswerFor.replace('{title}', 'Funding history') }), { target: { value: 'Saved first answer' } });
fireEvent.click(screen.getAllByRole('button', { name: copy.interviewPrepSaveAnswer })[0]);
}
await waitFor(() => expect(reads).toBe(2));
expect(screen.getByRole('textbox', { name })).toBe(answer);
expect(answer).toHaveValue('My unsaved sibling answer Øresund');
const updatedGroup = { ...board.groups[1], items: [{ ...board.groups[1].items[0], content: 'Current server answer' }] };
const updated = { ...board, groups: operation === 'delete' ? [updatedGroup] : [board.groups[0], updatedGroup] };
await act(async () => refresh.resolve({ data: updated }));
expect(screen.getByRole('textbox', { name })).toBe(answer);
expect(answer).toHaveValue('My unsaved sibling answer Øresund');
expect(mockedApi.patch).not.toHaveBeenCalledWith('/jobapplications/7/interview-prep/2', expect.anything());
fireEvent.click(screen.getByRole('button', { name: copy.interviewPrepDiscard }));
expect(answer).toHaveValue('Current server answer');
});
test.each(['en', 'nb'] as const)('same-application %s refresh failure and GET-only retry preserve an unsaved answer', async language => {
localStorage.setItem('uiLanguage', language);
const copy = translations[language];
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
let reads = 0;
mockedApi.get.mockImplementation((url: string) => url.endsWith('/interview-prep') && ++reads === 2 ? Promise.reject(new Error('Refresh failed')) : read(url));
mockedApi.patch.mockReset().mockResolvedValue({ data: board.groups[0].items[0] } as any);
render(<ApplicationInterviewPrep jobId={7} />);
const name = copy.interviewPrepAnswerFor.replace('{title}', 'Tell me about a conflict');
const answer = await screen.findByRole('textbox', { name });
fireEvent.change(answer, { target: { value: 'Keep across failed refresh' } });
fireEvent.click(screen.getByRole('checkbox', { name: copy.interviewPrepReadyLabel.replace('{title}', 'Funding history') }));
expect(await screen.findByText(copy.interviewPrepLoadFailed)).toBeVisible();
expect(screen.getByRole('textbox', { name })).toBe(answer);
expect(answer).toHaveValue('Keep across failed refresh');
fireEvent.click(screen.getByRole('button', { name: copy.retry }));
await waitFor(() => expect(screen.queryByText(copy.interviewPrepLoadFailed)).not.toBeInTheDocument());
expect(reads).toBe(3); expect(mockedApi.patch).toHaveBeenCalledTimes(1);
expect(screen.getByRole('textbox', { name })).toBe(answer);
expect(answer).toHaveValue('Keep across failed refresh');
});
test('marking readiness preserves that row answer draft because the write contains no answer', async () => {
mockedApi.get.mockReset(); routeGet();
mockedApi.patch.mockReset().mockResolvedValue({ data: board.groups[1].items[0] } as any);
render(<ApplicationInterviewPrep jobId={7} />);
const name = translations.en.interviewPrepAnswerFor.replace('{title}', 'Tell me about a conflict');
fireEvent.change(await screen.findByRole('textbox', { name }), { target: { value: 'Not saved by readiness' } });
fireEvent.click(screen.getByRole('checkbox', { name: 'Ready: Tell me about a conflict' }));
await waitFor(() => expect(mockedApi.get.mock.calls.filter(([url]) => String(url).endsWith('/interview-prep'))).toHaveLength(2));
expect(screen.getByRole('textbox', { name })).toHaveValue('Not saved by readiness');
expect(mockedApi.patch.mock.calls).toEqual([['/jobapplications/7/interview-prep/2', { isPrepared: true }]]);
});
test.each(['en', 'nb'] as const)('changing job clears %s answer drafts and a failed initial read offers only a GET retry', async language => {
localStorage.setItem('uiLanguage', language);
const copy = translations[language];
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
const current = deferredRead(); let currentReads = 0;
mockedApi.get.mockImplementation((url: string) => url === '/jobapplications/8/interview-prep' && ++currentReads === 1 ? current.promise : read(url));
const name = copy.interviewPrepAnswerFor.replace('{title}', 'Tell me about a conflict');
const view = render(<ApplicationInterviewPrep jobId={7} />);
fireEvent.change(await screen.findByRole('textbox', { name }), { target: { value: 'Private application seven answer' } });
await act(async () => view.rerender(<I18nProvider><ConfirmProvider><ApplicationInterviewPrep jobId={8} /></ConfirmProvider></I18nProvider>));
expect(screen.queryByRole('textbox', { name })).not.toBeInTheDocument();
await act(async () => current.reject(new Error('New application initial read failed')));
expect(screen.getByText(copy.interviewPrepLoadFailed)).toBeVisible();
expect(screen.queryByLabelText(copy.interviewPrepAddLabel)).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: copy.retry }));
expect(await screen.findByRole('textbox', { name })).toHaveValue('');
expect(currentReads).toBe(2);
expect(mockedApi.patch).not.toHaveBeenCalled(); expect(mockedApi.post).not.toHaveBeenCalled();
});
test.each(['success', 'failure', 'pending-newer'] as const)('a newer preparation refresh wins against an older %s completion', async completion => {
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
const older = deferredRead(); const newer = deferredRead();
let reads = 0;
mockedApi.get.mockImplementation((url: string) => url.endsWith('/interview-prep') && ++reads > 1 ? (reads === 2 ? older.promise : newer.promise) : read(url));
const firstWrite = deferredRead(); const secondWrite = deferredRead();
mockedApi.patch.mockReset().mockReturnValueOnce(firstWrite.promise).mockReturnValueOnce(secondWrite.promise);
render(<ApplicationInterviewPrep jobId={7} />);
fireEvent.click(await screen.findByRole('checkbox', { name: 'Ready: Funding history' }));
fireEvent.click(screen.getByRole('checkbox', { name: 'Ready: Tell me about a conflict' }));
await act(async () => firstWrite.resolve({ data: {} }));
await act(async () => secondWrite.resolve({ data: {} }));
expect(reads).toBe(3);
if (completion === 'pending-newer') {
await act(async () => older.resolve({ data: board }));
const region = within(screen.getByRole('region', { name: translations.en.interviewPrepTitle }));
expect(region.getByRole('progressbar', { name: translations.en.loading })).toBeVisible();
expect(region.getByLabelText(translations.en.interviewPrepAddLabel)).toBeVisible();
}
const currentBoard = { ...board, groups: [{ ...board.groups[0], items: [{ ...board.groups[0].items[0], title: 'Newest board' }] }] };
await act(async () => newer.resolve({ data: currentBoard }));
expect(await screen.findByText('Newest board')).toBeVisible();
fireEvent.change(screen.getByLabelText(translations.en.interviewPrepAddLabel), { target: { value: 'Current draft' } });
if (completion === 'success') await act(async () => older.resolve({ data: board }));
if (completion === 'failure') await act(async () => older.reject(new Error('Older refresh failure')));
expect(screen.getByText('Newest board')).toBeVisible();
expect(screen.queryByText(translations.en.interviewPrepLoadFailed)).not.toBeInTheDocument();
expect(screen.getByLabelText(translations.en.interviewPrepAddLabel)).toHaveValue('Current draft');
});
test.each(['prep', 'follow-up'] as const)('late %s write keeps its original target and cannot clear a new application draft', async surface => {
mockedApi.get.mockReset(); routeGet();
const write = deferredRead();
mockedApi.post.mockReset().mockReturnValueOnce(write.promise);
mockedApi.put.mockReset().mockReturnValueOnce(write.promise);
const component = (id: number) => surface === 'prep' ? <ApplicationInterviewPrep jobId={id} /> : <ApplicationFollowUp jobId={id} />;
const label = surface === 'prep' ? translations.en.interviewPrepAddLabel : translations.en.workspaceNextAction;
const view = render(component(7));
fireEvent.change(await screen.findByLabelText(label), { target: { value: 'Original application write' } });
fireEvent.click(screen.getByRole('button', { name: translations.en[surface === 'prep' ? 'interviewPrepAdd' : 'save'] }));
await act(async () => view.rerender(<I18nProvider><ConfirmProvider>{component(8)}</ConfirmProvider></I18nProvider>));
fireEvent.change(await screen.findByLabelText(label), { target: { value: 'New application draft' } });
await act(async () => write.resolve({ data: surface === 'prep' ? board.groups[0].items[0] : followUp }));
expect(screen.getByLabelText(label)).toHaveValue('New application draft');
expect(surface === 'prep' ? mockedApi.post : mockedApi.put).toHaveBeenCalledTimes(1);
expect((surface === 'prep' ? mockedApi.post : mockedApi.put).mock.calls[0][0]).toBe(`/jobapplications/7/${surface === 'prep' ? 'interview-prep' : 'follow-up'}`);
expect(mockedApi.get.mock.calls.filter(([url]) => url === '/jobapplications/7/interview-prep')).toHaveLength(surface === 'prep' ? 1 : 0);
});
test.each(['prep', 'follow-up'] as const)('late %s read cannot replace the current application or its draft', async surface => {
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
const old = deferredRead();
const suffix = surface === 'prep' ? 'interview-prep' : 'follow-up';
mockedApi.get.mockImplementation((url: string) => url === `/jobapplications/7/${suffix}` ? old.promise : read(url));
const component = (id: number) => surface === 'prep' ? <ApplicationInterviewPrep jobId={id} /> : <ApplicationFollowUp jobId={id} />;
const view = render(component(7));
await act(async () => view.rerender(<I18nProvider><ConfirmProvider>{component(8)}</ConfirmProvider></I18nProvider>));
const label = surface === 'prep' ? translations.en.interviewPrepAddLabel : translations.en.workspaceNextAction;
fireEvent.change(await screen.findByLabelText(label), { target: { value: 'Current application draft' } });
const oldData = surface === 'prep'
? { ...board, groups: [{ ...board.groups[0], items: [{ ...board.groups[0].items[0], title: 'Previous application only' }] }] }
: { ...followUp, nextAction: 'Previous application only' };
await act(async () => old.resolve({ data: oldData }));
expect(screen.getByLabelText(label)).toHaveValue('Current application draft');
expect(screen.queryByText('Previous application only')).not.toBeInTheDocument();
expect(screen.queryByDisplayValue('Previous application only')).not.toBeInTheDocument();
expect(mockedApi.post).not.toHaveBeenCalled(); expect(mockedApi.put).not.toHaveBeenCalled();
});
test.each(['prep', 'follow-up'] as const)('late %s read failure cannot hide the current draft', async surface => {
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
const old = deferredRead();
const suffix = surface === 'prep' ? 'interview-prep' : 'follow-up';
mockedApi.get.mockImplementation((url: string) => url === `/jobapplications/7/${suffix}` ? old.promise : read(url));
const component = (id: number) => surface === 'prep' ? <ApplicationInterviewPrep jobId={id} /> : <ApplicationFollowUp jobId={id} />;
const view = render(component(7));
await act(async () => view.rerender(<I18nProvider><ConfirmProvider>{component(8)}</ConfirmProvider></I18nProvider>));
const label = surface === 'prep' ? translations.en.interviewPrepAddLabel : translations.en.workspaceNextAction;
fireEvent.change(await screen.findByLabelText(label), { target: { value: 'Current application draft' } });
await act(async () => old.reject(new Error('Previous application failure')));
expect(screen.queryByText(translations.en[surface === 'prep' ? 'interviewPrepLoadFailed' : 'interviewFollowUpLoadFailed'])).not.toBeInTheDocument();
expect(screen.getByLabelText(label)).toHaveValue('Current application draft');
});
test.each(['prep', 'follow-up'] as const)('late %s finally cannot dismiss the current application loading state', async surface => {
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
const old = deferredRead(); const current = deferredRead();
const suffix = surface === 'prep' ? 'interview-prep' : 'follow-up';
mockedApi.get.mockImplementation((url: string) => url.endsWith(`/${suffix}`) ? (url.includes('/7/') ? old.promise : current.promise) : read(url));
const component = (id: number) => surface === 'prep' ? <ApplicationInterviewPrep jobId={id} /> : <ApplicationFollowUp jobId={id} />;
const view = render(component(7));
await act(async () => view.rerender(<I18nProvider><ConfirmProvider>{component(8)}</ConfirmProvider></I18nProvider>));
await act(async () => old.resolve({ data: surface === 'prep' ? board : followUp }));
const region = within(screen.getByRole('region', { name: translations.en[surface === 'prep' ? 'interviewPrepTitle' : 'interviewFollowUpTitle'] }));
expect(region.getByRole('progressbar', { name: translations.en.loading })).toBeVisible();
expect(region.queryByLabelText(translations.en[surface === 'prep' ? 'interviewPrepAddLabel' : 'workspaceNextAction'])).not.toBeInTheDocument();
await act(async () => current.resolve({ data: surface === 'prep' ? board : followUp }));
expect(await region.findByLabelText(translations.en[surface === 'prep' ? 'interviewPrepAddLabel' : 'workspaceNextAction'])).toBeVisible();
});
test('changing application resets parent drafts and a failed follow-up read retains a GET-only retry', async () => {
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
mockedApi.get.mockImplementation((url: string) => url === '/jobapplications/8/follow-up' ? Promise.reject(new Error('Current read failure')) : read(url));
const view = render(<ApplicationInterviewPrep jobId={7} />);
fireEvent.change(await screen.findByLabelText(translations.en.interviewPrepAddLabel), { target: { value: 'Application seven draft' } });
await screen.findByDisplayValue(followUp.nextAction);
await act(async () => view.rerender(<I18nProvider><ConfirmProvider><ApplicationInterviewPrep jobId={8} /></ConfirmProvider></I18nProvider>));
expect(await screen.findByLabelText(translations.en.interviewPrepAddLabel)).toHaveValue('');
expect(await screen.findByText(translations.en.interviewFollowUpLoadFailed)).toBeVisible();
const region = within(screen.getByRole('region', { name: translations.en.interviewFollowUpTitle }));
expect(region.queryByLabelText(translations.en.workspaceNextAction)).not.toBeInTheDocument();
mockedApi.get.mockImplementation(read);
fireEvent.click(region.getByRole('button', { name: translations.en.retry }));
expect(await region.findByLabelText(translations.en.workspaceNextAction)).toHaveValue(followUp.nextAction);
expect(mockedApi.put).not.toHaveBeenCalled();
});
test.each(['en', 'nb'] as const)('pending preparation deletion follows %s without a preparation reload or answer loss', async from => {
localStorage.setItem('uiLanguage', from);
const to = from === 'en' ? 'nb' : 'en';
mockedApi.get.mockReset(); routeGet();
mockedApi.delete.mockResolvedValue({ data: null } as any);
render(<ApplicationInterviewPrep jobId={7} />);
const opener = await screen.findByRole('button', { name: translations[from].interviewPrepDeleteLabel.replace('{title}', 'Funding history') });
const answerName = (language: 'en' | 'nb') => translations[language].interviewPrepAnswerFor.replace('{title}', 'Tell me about a conflict');
fireEvent.change(screen.getByRole('textbox', { name: answerName(from) }), { target: { value: 'My local STAR draft' } });
act(() => opener.focus()); fireEvent.click(opener);
const dialog = await screen.findByRole('dialog', { name: translations[from].interviewPrepDeleteTitle });
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: to })));
expect(screen.getByRole('dialog', { name: translations[to].interviewPrepDeleteTitle })).toBe(dialog);
expect(dialog).toHaveAccessibleDescription(translations[to].interviewPrepDeleteMessage.replace('{title}', 'Funding history'));
expect(mockedApi.get.mock.calls.filter(([url]) => String(url).endsWith('/interview-prep'))).toHaveLength(1);
expect(mockedApi.delete).not.toHaveBeenCalled();
expect(mockedApi.patch).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole('button', { name: translations[to].cancel }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
await waitFor(() => expect(opener).toHaveFocus());
expect(screen.getByRole('textbox', { name: answerName(to) })).toHaveValue('My local STAR draft');
fireEvent.click(opener);
fireEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: translations[to].interviewPrepDelete }));
await waitFor(() => expect(mockedApi.delete).toHaveBeenCalledTimes(1));
expect(mockedApi.delete).toHaveBeenCalledWith('/jobapplications/7/interview-prep/1');
expect(mockedApi.patch).not.toHaveBeenCalled();
});
test.each(['en', 'nb'] as const)('visible preparation read error follows %s without another preparation request', async from => {
localStorage.setItem('uiLanguage', from);
const to = from === 'en' ? 'nb' : 'en';
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
mockedApi.get.mockImplementation((url: string) => url.endsWith('/interview-prep') ? Promise.reject(new Error('synthetic preparation read failure')) : read(url));
render(<ApplicationInterviewPrep jobId={7} />);
expect(await screen.findByText(translations[from].interviewPrepLoadFailed)).toBeVisible();
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: to })));
expect(await screen.findByText(translations[to].interviewPrepLoadFailed)).toBeVisible();
expect(mockedApi.get.mock.calls.filter(([url]) => String(url).endsWith('/interview-prep'))).toHaveLength(1);
expect(mockedApi.post).not.toHaveBeenCalled();
expect(mockedApi.patch).not.toHaveBeenCalled();
expect(mockedApi.delete).not.toHaveBeenCalled();
});
test.each(['en', 'nb'] as const)('visible preparation mutation error follows %s without clearing the failure through a reload', async from => {
localStorage.setItem('uiLanguage', from);
const to = from === 'en' ? 'nb' : 'en';
mockedApi.get.mockReset(); routeGet();
mockedApi.post.mockReset().mockRejectedValue(new Error('synthetic preparation write failure'));
try {
render(<ApplicationInterviewPrep jobId={7} />);
await screen.findByText('Funding history');
fireEvent.change(screen.getByLabelText(translations[from].interviewPrepAddLabel), { target: { value: 'Research the role' } });
fireEvent.click(screen.getByRole('button', { name: translations[from].interviewPrepAdd }));
expect(await screen.findByText(translations[from].interviewPrepUpdateFailed)).toBeVisible();
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: to })));
expect(await screen.findByText(translations[to].interviewPrepUpdateFailed)).toBeVisible();
expect(mockedApi.get.mock.calls.filter(([url]) => String(url).endsWith('/interview-prep'))).toHaveLength(1);
expect(mockedApi.post).toHaveBeenCalledTimes(1);
expect(mockedApi.patch).not.toHaveBeenCalled();
expect(mockedApi.delete).not.toHaveBeenCalled();
} finally { mockedApi.post.mockReset(); }
});
describe.each(['en', 'nb'])('%s unknown interview categories', language => {
test.each(['constructor', 'toString', '__proto__'])('preserves %s as a category label', async category => {
window.localStorage.setItem('uiLanguage', language);
routeGet({ board: { ...board, groups: [{ ...board.groups[0], category }] } });
render(<ApplicationInterviewPrep jobId={7} />);
expect(await screen.findByText(category)).toBeInTheDocument();
expect(screen.getByText('Funding history')).toBeInTheDocument();
});
});
test.each((['en', 'nb'] as const).flatMap(from => (['pending', 'visible'] as const).map(timing => [from, timing] as const)))('answer save failure follows %s / %s and retains the draft for explicit retry', async (from, timing) => {
localStorage.setItem('uiLanguage', from);
const to = from === 'en' ? 'nb' : 'en';
mockedApi.get.mockReset(); routeGet();
mockedApi.patch.mockReset();
let reject!: (cause: unknown) => void;
const pending = new Promise((_, no) => { reject = no; });
mockedApi.patch.mockReturnValueOnce(pending as any).mockResolvedValueOnce({ data: { ...board.groups[1].items[0], content: 'My STAR answer Øresund' } } as any);
render(<ApplicationInterviewPrep jobId={7} />);
const answerName = (language: 'en' | 'nb') => translations[language].interviewPrepAnswerFor.replace('{title}', 'Tell me about a conflict');
fireEvent.change(await screen.findByRole('textbox', { name: answerName(from) }), { target: { value: 'My STAR answer Øresund' } });
fireEvent.click(screen.getByRole('button', { name: translations[from].interviewPrepSaveAnswer }));
await waitFor(() => expect(mockedApi.patch).toHaveBeenCalledTimes(1));
if (timing === 'pending') await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: to })));
await act(async () => reject(new Error('synthetic answer save failure')));
if (timing === 'visible') {
expect(await screen.findByText(translations[from].interviewPrepAnswerSaveFailed)).toBeVisible();
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: to })));
}
expect(await screen.findByText(translations[to].interviewPrepAnswerSaveFailed)).toBeVisible();
expect(screen.getByRole('textbox', { name: answerName(to) })).toHaveValue('My STAR answer Øresund');
expect(mockedApi.get.mock.calls.filter(([url]) => String(url).endsWith('/interview-prep'))).toHaveLength(1);
expect(mockedApi.patch).toHaveBeenCalledTimes(1);
routeGet({ board: { ...board, groups: board.groups.map(group => ({ ...group, items: group.items.map(item => item.id === 2 ? { ...item, content: 'My STAR answer Øresund' } : item) })) } });
fireEvent.click(screen.getByRole('button', { name: translations[to].interviewPrepSaveAnswer }));
await waitFor(() => expect(mockedApi.patch).toHaveBeenCalledTimes(2));
await waitFor(() => expect(screen.queryByText(translations[to].interviewPrepAnswerSaveFailed)).not.toBeInTheDocument());
expect(await screen.findByRole('textbox', { name: answerName(to) })).toHaveValue('My STAR answer Øresund');
expect(mockedApi.patch.mock.calls).toEqual(Array(2).fill(['/jobapplications/7/interview-prep/2', { content: 'My STAR answer Øresund' }]));
});
test("localizes interview categories while preserving user-authored preparation", async () => {
window.localStorage.setItem("uiLanguage", "nb");
routeGet();
render(<ApplicationInterviewPrep jobId={7} />);
expect((await screen.findAllByText("Selskapsresearch")).length).toBeGreaterThan(0);
expect(screen.getAllByText("Atferdsbaserte spørsmål").length).toBeGreaterThan(0);
expect(screen.getByText("Funding history")).toBeInTheDocument();
});
test("prep renders grouped items with progress and marks AI-sourced ones", async () => {
routeGet();
render(<ApplicationInterviewPrep jobId={7} />);
// Each label appears twice: once as the group heading, once as a category option in the add form.
expect((await screen.findAllByText("Company research")).length).toBeGreaterThan(0);
expect(screen.getAllByText("Behavioural questions").length).toBeGreaterThan(0);
expect(screen.getByText("Funding history")).toBeInTheDocument();
expect(screen.getByText("1 of 2 ready")).toBeInTheDocument();
expect(screen.getByText("From AI")).toBeInTheDocument();
});
test("delete tooltip describes its wrapper while the disabled button keeps its item name", async () => {
routeGet();
mockedApi.patch.mockReturnValueOnce(new Promise(() => {}));
render(<ApplicationInterviewPrep jobId={7} />);
const remove = await screen.findByRole("button", { name: "Delete: Funding history" });
expect(remove.parentElement).not.toHaveAttribute("aria-label");
fireEvent.click(screen.getByRole("checkbox", { name: "Ready: Funding history" }));
expect(remove).toBeDisabled();
fireEvent.mouseOver(remove.parentElement!);
expect(await screen.findByRole("tooltip")).toHaveTextContent("Delete");
expect(mockedApi.delete).not.toHaveBeenCalled();
});
test.each(['en', 'nb'] as const)('failed manual preparation add retains %s question and answers for explicit retry', async language => {
localStorage.setItem('uiLanguage', language);
const copy = translations[language];
mockedApi.get.mockReset(); routeGet();
mockedApi.post.mockReset().mockRejectedValueOnce(new Error('synthetic add failure')).mockResolvedValueOnce({ data: board.groups[0].items[0] } as any);
render(<ApplicationInterviewPrep jobId={7} />);
const answerName = copy.interviewPrepAnswerFor.replace('{title}', 'Tell me about a conflict');
fireEvent.change(await screen.findByRole('textbox', { name: answerName }), { target: { value: 'My local STAR answer' } });
fireEvent.change(screen.getByLabelText(copy.interviewPrepAddLabel), { target: { value: ' Ask about shift handover ' } });
fireEvent.click(screen.getByRole('button', { name: copy.interviewPrepAdd }));
expect(await screen.findByText(copy.interviewPrepUpdateFailed)).toBeVisible();
expect(screen.getByLabelText(copy.interviewPrepAddLabel)).toHaveValue(' Ask about shift handover ');
expect(screen.getByRole('textbox', { name: answerName })).toHaveValue('My local STAR answer');
expect(mockedApi.post).toHaveBeenCalledTimes(1);
expect(mockedApi.get.mock.calls.filter(([url]) => String(url).endsWith('/interview-prep'))).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: copy.interviewPrepAdd }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledTimes(2));
await waitFor(() => expect(screen.queryByText(copy.interviewPrepUpdateFailed)).not.toBeInTheDocument());
expect(screen.getByLabelText(copy.interviewPrepAddLabel)).toHaveValue('');
expect(screen.getByRole('textbox', { name: answerName })).toHaveValue('My local STAR answer');
expect(mockedApi.post.mock.calls).toEqual(Array(2).fill(['/jobapplications/7/interview-prep', { category: 'company-research', title: 'Ask about shift handover' }]));
expect(mockedApi.patch).not.toHaveBeenCalled();
expect(mockedApi.delete).not.toHaveBeenCalled();
});
test("adding a prep item posts the chosen category and title", async () => {
routeGet();
mockedApi.post.mockResolvedValue({ data: board.groups[0].items[0] } as any);
render(<ApplicationInterviewPrep jobId={7} />);
fireEvent.change(await screen.findByLabelText(/Add a question, topic or note/i), {
target: { value: "What does success look like?" },
});
fireEvent.click(screen.getByRole("button", { name: "Add" }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith(
"/jobapplications/7/interview-prep",
{ category: "company-research", title: "What does success look like?" },
));
});
test("starts a structured interview debrief without inventing answers", async () => {
routeGet();
mockedApi.post.mockResolvedValue({ data: board.groups[0].items[0] } as any);
render(<ApplicationInterviewPrep jobId={7} />);
fireEvent.click(await screen.findByRole("button", { name: "Start debrief" }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith(
"/jobapplications/7/interview-prep",
{
category: "debrief",
title: "Interview debrief",
content: expect.stringContaining("Questions asked:"),
},
));
expect(mockedApi.post.mock.calls[0][1]).toEqual(expect.objectContaining({
content: expect.not.stringMatching(/Acme|achievement|metric/i),
}));
});
test("marking an item ready patches it", async () => {
routeGet();
mockedApi.patch.mockResolvedValue({ data: board.groups[1].items[0] } as any);
render(<ApplicationInterviewPrep jobId={7} />);
fireEvent.click(await screen.findByRole("checkbox", { name: "Ready: Tell me about a conflict" }));
await waitFor(() => expect(mockedApi.patch).toHaveBeenCalledWith(
"/jobapplications/7/interview-prep/2", { isPrepared: true }));
});
test("an answer is only saved when the user asks", async () => {
routeGet();
mockedApi.patch.mockResolvedValue({ data: board.groups[1].items[0] } as any);
render(<ApplicationInterviewPrep jobId={7} />);
const boxes = await screen.findAllByPlaceholderText(/Your answer, in your own words/i);
fireEvent.change(boxes[1], { target: { value: "My STAR answer" } });
// Typing alone must not persist anything.
expect(mockedApi.patch).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: /Save answer/i }));
await waitFor(() => expect(mockedApi.patch).toHaveBeenCalledWith(
"/jobapplications/7/interview-prep/2", { content: "My STAR answer" }));
});
test("deleting a prep item calls delete", async () => {
routeGet();
mockedApi.delete.mockResolvedValue({ data: undefined } as any);
render(<ApplicationInterviewPrep jobId={7} />);
fireEvent.click(await screen.findByRole("button", { name: "Delete: Funding history" }));
fireEvent.click(await screen.findByRole("button", { name: "Delete" }));
await waitFor(() => expect(mockedApi.delete).toHaveBeenCalledWith("/jobapplications/7/interview-prep/1"));
});
test("empty prep shows a useful empty state", async () => {
routeGet({ board: { groups: [], total: 0, prepared: 0, percent: 0, isInterviewStage: false, aiSuggestionCount: 0 } });
render(<ApplicationInterviewPrep jobId={7} />);
expect(await screen.findByText(/Nothing prepared yet/i)).toBeInTheDocument();
expect(screen.getByText(/has not reached an interview stage/i)).toBeInTheDocument();
});
test("AI preparation uses the linked CV and only saves after explicit acceptance", async () => {
routeGet();
mockedApi.post.mockImplementation((url: string) => {
if (url.endsWith("/ai/generate")) {
return Promise.resolve({ data: { result: { text: "## Technical\nExplain dependency injection." } } } as any);
}
return Promise.resolve({ data: board.groups[0].items[0] } as any);
});
render(<ApplicationInterviewPrep jobId={7} />);
expect(await screen.findByText("Backend CV")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Generate preparation" }));
expect(await screen.findByText(/Explain dependency injection/i)).toBeInTheDocument();
expect(mockedApi.post).toHaveBeenCalledWith(
"/jobapplications/7/ai/generate",
expect.objectContaining({ module: "interview", targetLanguage: "en" }),
);
expect(mockedApi.post).not.toHaveBeenCalledWith(
"/jobapplications/7/interview-prep",
expect.anything(),
);
fireEvent.click(screen.getByRole("button", { name: "Add to preparation" }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith(
"/jobapplications/7/interview-prep",
expect.objectContaining({ source: "ai", content: expect.stringContaining("dependency injection") }),
));
});
test('late generation cannot offer another application the previous application suggestion', async () => {
mockedApi.get.mockReset(); routeGet();
let finish!: (value: any) => void;
mockedApi.post.mockReset().mockReturnValueOnce(new Promise(resolve => { finish = resolve; }) as any);
const view = render(<ApplicationInterviewPrep jobId={7} />);
await screen.findByText('Backend CV');
fireEvent.change(screen.getByLabelText(translations.en.coverAiAdditionalInstructions), { target: { value: 'Private instructions for application seven' } });
fireEvent.click(screen.getByRole('button', { name: translations.en.interviewAiGenerate }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledTimes(1));
await act(async () => view.rerender(<I18nProvider><ConfirmProvider><ApplicationInterviewPrep jobId={8} /></ConfirmProvider></I18nProvider>));
await act(async () => finish({ data: { result: { text: 'Only for application seven' } } }));
const assistant = within(screen.getByRole('region', { name: translations.en.interviewAiTitle }));
expect(assistant.queryByText('Only for application seven')).not.toBeInTheDocument();
expect(assistant.queryByRole('button', { name: translations.en.interviewAiAddToPrep })).not.toBeInTheDocument();
expect(assistant.getByLabelText(translations.en.coverAiAdditionalInstructions)).toHaveValue('');
expect(mockedApi.post).toHaveBeenCalledTimes(1);
});
test('completed AI suggestion is scoped to its application instead of becoming a new application draft', async () => {
mockedApi.get.mockReset(); routeGet();
mockedApi.post.mockReset().mockResolvedValue({ data: { result: { text: 'Prepared for application seven only' } } } as any);
const view = render(<ApplicationInterviewPrep jobId={7} />);
await screen.findByText('Backend CV');
fireEvent.click(screen.getByRole('button', { name: translations.en.interviewAiGenerate }));
expect(await screen.findByText('Prepared for application seven only')).toBeVisible();
await act(async () => view.rerender(<I18nProvider><ConfirmProvider><ApplicationInterviewPrep jobId={8} /></ConfirmProvider></I18nProvider>));
const assistant = within(screen.getByRole('region', { name: translations.en.interviewAiTitle }));
expect(assistant.queryByText('Prepared for application seven only')).not.toBeInTheDocument();
expect(assistant.queryByRole('button', { name: translations.en.interviewAiAddToPrep })).not.toBeInTheDocument();
expect(mockedApi.post).not.toHaveBeenCalledWith('/jobapplications/8/interview-prep', expect.anything());
});
test('late accepted suggestion does not reload the previous application board into the current application', async () => {
mockedApi.get.mockReset(); routeGet();
let finish!: (value: any) => void;
mockedApi.post.mockReset().mockResolvedValueOnce({ data: { result: { text: 'Application seven suggestion' } } } as any).mockReturnValueOnce(new Promise(resolve => { finish = resolve; }) as any);
const view = render(<ApplicationInterviewPrep jobId={7} />);
await screen.findByText('Backend CV');
fireEvent.click(screen.getByRole('button', { name: translations.en.interviewAiGenerate }));
await screen.findByText('Application seven suggestion');
fireEvent.click(screen.getByRole('button', { name: translations.en.interviewAiAddToPrep }));
await waitFor(() => expect(mockedApi.post).toHaveBeenCalledTimes(2));
await act(async () => view.rerender(<I18nProvider><ConfirmProvider><ApplicationInterviewPrep jobId={8} /></ConfirmProvider></I18nProvider>));
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith('/jobapplications/8/interview-prep'));
await act(async () => finish({ data: board.groups[0].items[0] }));
expect(mockedApi.get.mock.calls.filter(([url]) => url === '/jobapplications/7/interview-prep')).toHaveLength(1);
expect(mockedApi.get.mock.calls.filter(([url]) => url === '/jobapplications/8/interview-prep')).toHaveLength(1);
expect(mockedApi.post.mock.calls[1]).toEqual(['/jobapplications/7/interview-prep', expect.objectContaining({ source: 'ai', content: 'Application seven suggestion' })]);
});
test.each(['en', 'nb'] as const)('pending linked CV is loading, not an empty selection (%s)', async language => {
localStorage.setItem('uiLanguage', language);
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
let finish!: (value: any) => void;
const pending = new Promise(resolve => { finish = resolve; });
mockedApi.get.mockImplementation((url: string) => url.endsWith('/cv') ? pending as any : read(url));
render(<ApplicationInterviewPrep jobId={7} />);
const assistant = within(screen.getByRole('region', { name: translations[language].interviewAiTitle }));
expect(assistant.getByRole('progressbar', { name: translations[language].loading })).toBeVisible();
expect(assistant.queryByText(translations[language].interviewAiSelectCv)).not.toBeInTheDocument();
expect(assistant.getByRole('button', { name: translations[language].interviewAiGenerate })).toBeDisabled();
await act(async () => finish({ data: { attachedVariantId: null, attachedVariantName: null } }));
expect(await assistant.findByText(translations[language].interviewAiSelectCv)).toBeVisible();
expect(assistant.queryByRole('progressbar')).not.toBeInTheDocument();
expect(mockedApi.post).not.toHaveBeenCalled();
});
test.each(['en', 'nb'] as const)('linked-CV failure has current-language GET-only retry and preserves instructions (%s)', async from => {
localStorage.setItem('uiLanguage', from);
const to = from === 'en' ? 'nb' : 'en';
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
let cvReads = 0;
mockedApi.get.mockImplementation((url: string) => url.endsWith('/cv') && ++cvReads === 1 ? Promise.reject(new Error('synthetic linked-CV failure')) : read(url));
render(<ApplicationInterviewPrep jobId={7} />);
const region = screen.getByRole('region', { name: translations[from].interviewAiTitle });
const assistant = within(region);
expect(await assistant.findByText(translations[from].assetsLoadFailed)).toBeVisible();
expect(assistant.queryByText(translations[from].interviewAiSelectCv)).not.toBeInTheDocument();
fireEvent.change(assistant.getByLabelText(translations[from].coverAiAdditionalInstructions), { target: { value: 'Keep my context Øresund' } });
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: to })));
expect(assistant.getByText(translations[to].assetsLoadFailed)).toBeVisible();
expect(cvReads).toBe(1);
expect(assistant.getByRole('combobox', { name: translations[to].coverAiDocumentLanguage })).toHaveTextContent(translations[to][from === 'en' ? 'languageEnglish' : 'languageNorwegianBokmal']);
fireEvent.click(assistant.getByRole('button', { name: translations[to].retry }));
expect(await assistant.findByText('Backend CV')).toBeVisible();
expect(cvReads).toBe(2);
expect(assistant.getByLabelText(translations[to].coverAiAdditionalInstructions)).toHaveValue('Keep my context Øresund');
expect(mockedApi.post).not.toHaveBeenCalled(); expect(mockedApi.patch).not.toHaveBeenCalled(); expect(mockedApi.put).not.toHaveBeenCalled();
});
test.each(['en', 'nb'] as const)('changing application hides the previous linked CV while the new read is pending (%s)', async language => {
localStorage.setItem('uiLanguage', language);
mockedApi.get.mockReset(); routeGet();
const read = mockedApi.get.getMockImplementation()!;
let finish!: (value: any) => void;
const pending = new Promise(resolve => { finish = resolve; });
mockedApi.get.mockImplementation((url: string) => url === '/jobapplications/8/cv' ? pending as any : read(url));
const view = render(<ApplicationInterviewPrep jobId={7} />);
await screen.findByText('Backend CV');
await act(async () => view.rerender(<I18nProvider><ConfirmProvider><ApplicationInterviewPrep jobId={8} /></ConfirmProvider></I18nProvider>));
const assistant = within(screen.getByRole('region', { name: translations[language].interviewAiTitle }));
expect(assistant.queryByText('Backend CV')).not.toBeInTheDocument();
expect(assistant.getByRole('progressbar', { name: translations[language].loading })).toBeVisible();
await act(async () => finish({ data: { attachedVariantId: 8, attachedVariantName: 'Current application CV' } }));
expect(await assistant.findByText('Current application CV')).toBeVisible();
expect(mockedApi.post).not.toHaveBeenCalled();
});
test("prep surfaces a load error", async () => {
mockedApi.get.mockRejectedValue(new Error("boom"));
render(<ApplicationInterviewPrep jobId={7} />);
expect(await screen.findByText(/Could not load interview preparation/i)).toBeInTheDocument();
});
// ---------- follow-up ----------
test.each(['en', 'nb'] as const)('failed follow-up save retains editable %s drafts and retries only the explicit write', async language => {
localStorage.setItem('uiLanguage', language);
const copy = translations[language];
mockedApi.get.mockReset(); routeGet();
mockedApi.put.mockReset().mockRejectedValueOnce(new Error('synthetic follow-up save failure')).mockResolvedValueOnce({ data: { ...followUp, followUpAt: '2026-12-01', nextAction: 'Discuss offer Øresund' } } as any);
render(<ApplicationFollowUp jobId={7} />);
fireEvent.change(await screen.findByLabelText(copy.interviewFollowUpDate), { target: { value: '2026-12-01' } });
fireEvent.change(screen.getByLabelText(copy.workspaceNextAction), { target: { value: 'Discuss offer Øresund' } });
fireEvent.click(screen.getByRole('button', { name: copy.save }));
expect(await screen.findByText(copy.interviewFollowUpSaveFailed)).toBeVisible();
expect(screen.getByLabelText(copy.interviewFollowUpDate)).toHaveValue('2026-12-01');
expect(screen.getByLabelText(copy.workspaceNextAction)).toHaveValue('Discuss offer Øresund');
const save = screen.getByRole('button', { name: copy.save });
expect(save).toBeEnabled(); expect(mockedApi.put).toHaveBeenCalledTimes(1); expect(mockedApi.get).toHaveBeenCalledTimes(1);
fireEvent.click(save);
await waitFor(() => expect(mockedApi.put).toHaveBeenCalledTimes(2));
await waitFor(() => expect(screen.queryByText(copy.interviewFollowUpSaveFailed)).not.toBeInTheDocument());
expect(mockedApi.put.mock.calls).toEqual(Array(2).fill(['/jobapplications/7/follow-up', { followUpAt: '2026-12-01', nextAction: 'Discuss offer Øresund' }]));
expect(mockedApi.get).toHaveBeenCalledTimes(1);
expect(screen.getByLabelText(copy.workspaceNextAction)).toHaveValue('Discuss offer Øresund');
});
test.each(['en', 'nb'] as const)('failed initial follow-up read offers %s GET-only retry without editable defaults', async language => {
localStorage.setItem('uiLanguage', language);
const copy = translations[language];
mockedApi.get.mockReset().mockRejectedValueOnce(new Error('synthetic follow-up read failure')).mockResolvedValueOnce({ data: followUp } as any);
mockedApi.put.mockReset();
render(<ApplicationFollowUp jobId={7} />);
expect(await screen.findByText(copy.interviewFollowUpLoadFailed)).toBeVisible();
expect(screen.queryByLabelText(copy.interviewFollowUpDate)).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: copy.save })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: copy.retry }));
expect(await screen.findByLabelText(copy.interviewFollowUpDate)).toHaveValue('2026-07-26');
expect(screen.getByLabelText(copy.workspaceNextAction)).toHaveValue(followUp.nextAction);
expect(mockedApi.get.mock.calls).toEqual(Array(2).fill(['/jobapplications/7/follow-up']));
expect(mockedApi.put).not.toHaveBeenCalled();
});
test.each(['en', 'nb'] as const)('follow-up language switch from %s preserves the unsaved date and next action without a read', async from => {
localStorage.setItem('uiLanguage', from);
const to = from === 'en' ? 'nb' : 'en';
mockedApi.get.mockReset(); routeGet();
mockedApi.put.mockReset().mockResolvedValue({ data: followUp } as any);
render(<ApplicationFollowUp jobId={7} />);
fireEvent.change(await screen.findByLabelText(translations[from].interviewFollowUpDate), { target: { value: '2026-12-01' } });
fireEvent.change(screen.getByLabelText(translations[from].workspaceNextAction), { target: { value: 'Discuss the offer Øresund' } });
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: to })));
expect(screen.getByLabelText(translations[to].interviewFollowUpDate)).toHaveValue('2026-12-01');
expect(screen.getByLabelText(translations[to].workspaceNextAction)).toHaveValue('Discuss the offer Øresund');
expect(mockedApi.get).toHaveBeenCalledTimes(1);
expect(mockedApi.put).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: translations[to].save }));
await waitFor(() => expect(mockedApi.put).toHaveBeenCalledTimes(1));
expect(mockedApi.put).toHaveBeenCalledWith('/jobapplications/7/follow-up', { followUpAt: '2026-12-01', nextAction: 'Discuss the offer Øresund' });
});
test.each((['en', 'nb'] as const).flatMap(from => (['read', 'save'] as const).map(operation => [from, operation] as const)))('follow-up %s %s error stays current without another read', async (from, operation) => {
localStorage.setItem('uiLanguage', from);
const to = from === 'en' ? 'nb' : 'en';
mockedApi.get.mockReset(); routeGet();
mockedApi.put.mockReset();
const key = operation === 'read' ? 'interviewFollowUpLoadFailed' : 'interviewFollowUpSaveFailed';
if (operation === 'read') mockedApi.get.mockRejectedValue(new Error('synthetic follow-up read failure'));
else mockedApi.put.mockRejectedValue(new Error('synthetic follow-up save failure'));
try {
render(<ApplicationFollowUp jobId={7} />);
if (operation === 'save') {
await screen.findByLabelText(translations[from].interviewFollowUpDate);
fireEvent.click(screen.getByRole('button', { name: translations[from].save }));
}
expect(await screen.findByText(translations[from][key])).toBeVisible();
await act(async () => window.dispatchEvent(new StorageEvent('storage', { key: 'uiLanguage', newValue: to })));
expect(await screen.findByText(translations[to][key])).toBeVisible();
expect(mockedApi.get).toHaveBeenCalledTimes(1);
expect(mockedApi.put).toHaveBeenCalledTimes(operation === 'save' ? 1 : 0);
} finally { mockedApi.put.mockReset(); }
});
test("follow-up loads the existing date and open checklist tasks", async () => {
routeGet();
render(<ApplicationFollowUp jobId={7} />);
expect(await screen.findByDisplayValue("2026-07-26")).toBeInTheDocument();
expect(screen.getByDisplayValue("Chase recruiter")).toBeInTheDocument();
expect(screen.getByText(/1 open follow-up task on the checklist/i)).toBeInTheDocument();
});
test("saving a follow-up sends the date and next action", async () => {
routeGet();
mockedApi.put.mockResolvedValue({ data: followUp } as any);
render(<ApplicationFollowUp jobId={7} />);
fireEvent.change(await screen.findByLabelText(/Follow up on/i), { target: { value: "2026-08-01" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(mockedApi.put).toHaveBeenCalledWith(
"/jobapplications/7/follow-up",
{ followUpAt: "2026-08-01", nextAction: "Chase recruiter" },
));
});
test("no follow-up shows an empty state", async () => {
routeGet({ followUp: { followUpAt: null, nextAction: null, responseReceived: false, openFollowUpTasks: 0 } });
render(<ApplicationFollowUp jobId={7} />);
expect(await screen.findByText(/No follow-up scheduled/i)).toBeInTheDocument();
});