Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/components/Calendar/Components/CalendarComponent.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,23 @@ describe('CalendarComponent', () => {
expect(await screen.findByText('70.0 server.kg')).toBeInTheDocument();
});

test('still renders the detail panel when the official body weight category is missing', async () => {
// Before the fix the body weight query threw and, gated behind isSuccess,
// hung the whole calendar on its spinner.
(getBodyWeightCategory as Mock).mockImplementation(() => Promise.resolve(null));

renderComponent();

const day = await screen.findByTestId(`day-${dateToYYYYMMDD(new Date(currentYear, currentMonth, 1))}`);
await user.click(day);
await user.click(await screen.findByText('measurements.measurements'));

// The panel rendered its content rather than staying on the spinner
expect(await screen.findByText('Body Fat')).toBeInTheDocument();
// getWeights is skipped entirely when there is no category to read from
expect(getWeights).not.toHaveBeenCalled();
});

test('reads the month as the instants it spans in the browser timezone', async () => {
const start = new Date(currentYear, currentMonth, 1).toISOString();
const end = new Date(currentYear, currentMonth + 1, 1).toISOString();
Expand Down
4 changes: 2 additions & 2 deletions src/components/Measurements/api/bodyWeight.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ describe("weight service tests", () => {
vi.clearAllMocks();
});

test('an empty category response raises a clear error', async () => {
test('an empty category response resolves to null, not an error', async () => {

(axios.get as Mock).mockImplementation(() => Promise.resolve({
data: { count: 0, next: null, previous: null, results: [] }
}));

await expect(getBodyWeightCategory()).rejects.toThrow('No official body weight category');
await expect(getBodyWeightCategory()).resolves.toBeNull();
});

test('GET the official body weight category', async () => {
Expand Down
14 changes: 7 additions & 7 deletions src/components/Measurements/api/bodyWeight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,22 @@ import { ApiMeasurementCategoryType } from '@/types';
import axios from 'axios';

/*
* Fetch the user's official body weight category
*
* The server guarantees that every user has exactly one
* Fetch the user's official body weight category, or null if they have none
* yet. It is created lazily, so fixture-created accounts (the signal is
* @disable_for_loaddata) can lack it; null lets callers treat that as "no body
* weight" instead of throwing. null, not undefined, as this resolves a
* react-query query. A request failure still rejects through axios.
*/
export const getBodyWeightCategory = async (): Promise<MeasurementCategory> => {
export const getBodyWeightCategory = async (): Promise<MeasurementCategory | null> => {
const url = makeUrl(API_MEASUREMENTS_CATEGORY_PATH, {
query: { metric_type: METRIC_TYPE_BODY_WEIGHT, is_official: 'true' }
});
const { data } = await axios.get<ResponseType<ApiMeasurementCategoryType>>(url, {
headers: makeHeader(),
});

// The server guarantees the category exists; still fail with a clear
// message instead of a TypeError should that ever break
if (data.results.length === 0) {
throw new Error('No official body weight category found');
return null;
}

return MeasurementCategory.fromJson(data.results[0]);
Expand Down
15 changes: 15 additions & 0 deletions src/components/Measurements/queries/bodyWeight.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,21 @@ describe("body weight queries", () => {
(deleteMeasurementEntry as Mock).mockResolvedValue(undefined);
});

test('resolves to an empty history when the category is missing', async () => {

(getBodyWeightCategory as Mock).mockResolvedValue(null);

const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: { children: React.ReactNode }) =>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;

const { result } = renderHook(() => useBodyWeightQuery(), { wrapper });

await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(result.current.data).toEqual([]);
expect(getWeights).not.toHaveBeenCalled();
});

// Body weight rows are measurement rows, so a write through the measurement
// mutations has to refresh the weight view as well
test.each(entryMutations)('an entry %s invalidates the body weight view', async (_name, useWrite) => {
Expand Down
4 changes: 4 additions & 0 deletions src/components/Measurements/queries/bodyWeight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ export function useBodyWeightQuery(filtersetQueryEntries: object = {}) {
queryKey: [QueryKey.MEASUREMENT_ENTRIES, OFFICIAL_BODY_WEIGHT, filtersetQueryEntries],
queryFn: async () => {
const category = await queryClient.ensureQueryData(bodyWeightCategoryQueryOptions);
// No category yet: no entries to read (see getBodyWeightCategory).
if (category === null) {
return [];
}
return getWeights(category, filtersetQueryEntries);
},
// Widening the range refetches, and the chart would otherwise drop
Expand Down
12 changes: 11 additions & 1 deletion src/components/Measurements/screens/BodyWeight.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,18 @@ export const BodyWeight = (props: { planPeriods?: PlanPeriod[] }) => {
return <LoadingPlaceholder />;
}

// No official category yet: show the empty state (the FAB creates one)
// instead of dereferencing a null category below.
if (!categoryQuery.data) {
return <WgerContainerRightSidebar
title={t("weight")}
mainContent={<OverviewEmpty />}
fab={<AddBodyWeightEntryFab />}
/>;
}

// Entries without their own unit fall back to the one of the category
const categoryUnit = categoryQuery.data!.unit;
const categoryUnit = categoryQuery.data.unit;

// The range as it is labelled: the lead the chart averages over is not part
// of it, and the table would list those rows as if they were
Expand Down