feat(jobs): improve discovery result states
CI and Deploy / test (pull_request) Successful in 4m42s
CI and Deploy / deploy (pull_request) Has been skipped

This commit is contained in:
cesnimda
2026-08-10 10:42:45 +02:00
parent 3d219eb4ac
commit 3f74b236ef
2 changed files with 85 additions and 11 deletions
+42
View File
@@ -8,6 +8,8 @@ import JobDiscoveryPage from "./views/JobDiscoveryPage";
jest.mock("./api", () => ({ api: { get: jest.fn() } }));
const mockedApi = api as jest.Mocked<typeof api>;
afterEach(() => jest.clearAllMocks());
test("shows honest source metadata and offers the existing reviewed save flow", async () => {
mockedApi.get.mockResolvedValue({ data: [{ id: "abc", title: "Backend Developer", company: "Acme", location: "OSLO", modifiedAt: "2026-08-01T10:00:00Z", deadline: "2026-08-15T23:59:59Z", url: "https://arbeidsplassen.nav.no/stillinger/stilling/abc", source: "nav", sourceName: "NAV Arbeidsplassen", acquisitionType: "searched", retrievedAt: "2026-08-10T10:00:00Z", countryCode: "NO" }] } as any);
render(<MemoryRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}><JobDiscoveryPage /></MemoryRouter>);
@@ -22,3 +24,43 @@ test("shows honest source metadata and offers the existing reviewed save flow",
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith("/job-discovery/search", { params: { q: "backend", location: undefined } }));
expect(screen.getByRole("button", { name: "Save to tracker" })).toBeInTheDocument();
});
test("distinguishes the initial guidance from a completed empty search", async () => {
mockedApi.get.mockResolvedValue({ data: [] } as any);
render(<MemoryRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}><JobDiscoveryPage /></MemoryRouter>);
expect(screen.getByText("Search recent active vacancies by role, company, or municipality.")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));
expect(await screen.findByText(/No active vacancies matched this search/)).toBeInTheDocument();
expect(screen.queryByText("Search recent active vacancies by role, company, or municipality.")).not.toBeInTheDocument();
});
test("retries the last submitted search after an error", async () => {
mockedApi.get.mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce({ data: [] } as any);
render(<MemoryRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}><JobDiscoveryPage /></MemoryRouter>);
fireEvent.change(screen.getByLabelText("Role or company"), { target: { value: " utvikler " } });
fireEvent.change(screen.getByLabelText("Municipality"), { target: { value: " Oslo " } });
fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));
fireEvent.click(await screen.findByRole("button", { name: "Retry" }));
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledTimes(2));
expect(mockedApi.get).toHaveBeenLastCalledWith("/job-discovery/search", { params: { q: "utvikler", location: "Oslo" } });
});
test("sorts returned vacancies by title", async () => {
mockedApi.get.mockResolvedValue({ data: [
{ id: "2", title: "Zoologist", url: "https://arbeidsplassen.nav.no/2", source: "nav", countryCode: "NO" },
{ id: "1", title: "Analyst", url: "https://arbeidsplassen.nav.no/1", source: "nav", countryCode: "NO" },
] } as any);
render(<MemoryRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}><JobDiscoveryPage /></MemoryRouter>);
fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));
await screen.findByText("2 vacancies found");
fireEvent.mouseDown(screen.getByRole("combobox", { name: "Sort results" }));
fireEvent.click(await screen.findByRole("option", { name: "Title AZ" }));
const titles = screen.getAllByRole("heading", { level: 6 }).map((element) => element.textContent);
expect(titles).toEqual(["Analyst", "Zoologist"]);
});
+43 -11
View File
@@ -1,5 +1,5 @@
import { FormEvent, useState } from "react";
import { Alert, Box, Button, Card, CardActions, CardContent, Chip, CircularProgress, Stack, TextField, Typography } from "@mui/material";
import { FormEvent, useMemo, useState } from "react";
import { Alert, Box, Button, Card, CardActions, CardContent, Chip, CircularProgress, MenuItem, Stack, TextField, Typography } from "@mui/material";
import SearchIcon from "@mui/icons-material/Search";
import AddIcon from "@mui/icons-material/Add";
import { useNavigate } from "react-router-dom";
@@ -21,6 +21,7 @@ type DiscoveredJob = {
};
const formatDate = (value?: string) => value ? new Date(value).toLocaleDateString() : null;
type SortOrder = "updated" | "deadline" | "title";
export default function JobDiscoveryPage() {
const navigate = useNavigate();
@@ -29,16 +30,34 @@ export default function JobDiscoveryPage() {
const [jobs, setJobs] = useState<DiscoveredJob[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [hasSearched, setHasSearched] = useState(false);
const [lastSearch, setLastSearch] = useState({ query: "", location: "" });
const [sortOrder, setSortOrder] = useState<SortOrder>("updated");
const search = async (event: FormEvent) => {
event.preventDefault(); setLoading(true); setError("");
const runSearch = async (nextQuery: string, nextLocation: string) => {
setLoading(true); setError(""); setJobs([]); setHasSearched(true); setLastSearch({ query: nextQuery, location: nextLocation });
try {
const response = await api.get<DiscoveredJob[]>("/job-discovery/search", { params: { q: query || undefined, location: location || undefined } });
const response = await api.get<DiscoveredJob[]>("/job-discovery/search", { params: { q: nextQuery || undefined, location: nextLocation || undefined } });
setJobs(response.data ?? []);
} catch { setError("NAV job discovery is temporarily unavailable."); }
finally { setLoading(false); }
};
const search = (event: FormEvent) => {
event.preventDefault();
void runSearch(query.trim(), location.trim());
};
const sortedJobs = useMemo(() => [...jobs].sort((left, right) => {
if (sortOrder === "title") return left.title.localeCompare(right.title);
if (sortOrder === "deadline") {
const leftDeadline = left.deadline ? new Date(left.deadline).getTime() : Number.MAX_SAFE_INTEGER;
const rightDeadline = right.deadline ? new Date(right.deadline).getTime() : Number.MAX_SAFE_INTEGER;
return leftDeadline - rightDeadline;
}
return new Date(right.modifiedAt || 0).getTime() - new Date(left.modifiedAt || 0).getTime();
}), [jobs, sortOrder]);
return (
<Stack spacing={3}>
<Box component="form" onSubmit={search} sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", md: "2fr 1fr auto" }, gap: 1.5 }}>
@@ -47,15 +66,27 @@ export default function JobDiscoveryPage() {
<Button type="submit" variant="contained" startIcon={loading ? <CircularProgress size={18} color="inherit" /> : <SearchIcon />} disabled={loading}>Search NAV</Button>
</Box>
<Alert severity="info">Official Norwegian vacancies from NAV. FINN, Indeed and LinkedIn jobs can still be captured by URL.</Alert>
{error ? <Alert severity="error">{error}</Alert> : null}
{!loading && jobs.length === 0 ? <Typography color="text.secondary">Search recent active vacancies by role, company, or municipality.</Typography> : null}
{error ? <Alert severity="error" action={<Button color="inherit" onClick={() => void runSearch(lastSearch.query, lastSearch.location)} disabled={loading}>Retry</Button>}>{error}</Alert> : null}
{!loading && !hasSearched ? <Typography color="text.secondary">Search recent active vacancies by role, company, or municipality.</Typography> : null}
{!loading && hasSearched && !error && jobs.length === 0 ? <Alert severity="info">No active vacancies matched this search. Try a broader role, company, or municipality.</Alert> : null}
{loading ? <Typography role="status" color="text.secondary">Searching NAV vacancies</Typography> : null}
{jobs.length > 0 ? (
<Box sx={{ display: "flex", gap: 2, alignItems: { xs: "stretch", sm: "center" }, justifyContent: "space-between", flexDirection: { xs: "column", sm: "row" } }}>
<Typography role="status">{jobs.length} {jobs.length === 1 ? "vacancy" : "vacancies"} found</Typography>
<TextField select size="small" label="Sort results" value={sortOrder} onChange={(event) => setSortOrder(event.target.value as SortOrder)} sx={{ minWidth: 190 }}>
<MenuItem value="updated">Recently updated</MenuItem>
<MenuItem value="deadline">Deadline soonest</MenuItem>
<MenuItem value="title">Title AZ</MenuItem>
</TextField>
</Box>
) : null}
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", lg: "repeat(2, minmax(0, 1fr))" }, gap: 2 }}>
{jobs.map((job) => (
<Card key={job.id} variant="outlined">
{sortedJobs.map((job) => (
<Card key={job.id} variant="outlined" sx={{ display: "flex", flexDirection: "column" }}>
<CardContent>
<Chip label={job.sourceName || job.source.toUpperCase()} size="small" color="primary" variant="outlined" sx={{ mb: 1 }} />
<Typography variant="h6" sx={{ fontWeight: 800 }}>{job.title}</Typography>
<Typography color="text.secondary">{[job.company, job.location].filter(Boolean).join(" · ")}</Typography>
<Typography color="text.secondary">{[job.company, job.location || "Location not provided"].filter(Boolean).join(" · ")}</Typography>
<Stack spacing={0.25} sx={{ mt: 1 }}>
<Typography variant="caption" color="text.secondary">
{job.acquisitionType === "searched" ? "Searched listing" : "Source type unavailable"}
@@ -63,9 +94,10 @@ export default function JobDiscoveryPage() {
</Typography>
{formatDate(job.modifiedAt) ? <Typography variant="caption" color="text.secondary">Listing updated {formatDate(job.modifiedAt)}</Typography> : null}
{formatDate(job.deadline) ? <Typography variant="body2" color="text.primary">Application deadline: {formatDate(job.deadline)}</Typography> : null}
<Typography variant="caption" color="text.secondary">Work arrangement not provided by this source</Typography>
</Stack>
</CardContent>
<CardActions>
<CardActions sx={{ mt: "auto" }}>
<Button href={job.url} target="_blank" rel="noreferrer">View listing</Button>
<Button startIcon={<AddIcon />} onClick={() => navigate("/jobs?add=" + encodeURIComponent(job.url))}>Save to tracker</Button>
</CardActions>