Return

All tests / src/hooks useWeather.ts

100% Statements 15/15
100% Branches 0/0
100% Functions 2/2
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 574x 4x 4x 4x                   4x                       4x   4x             7x 6x 6x 6x     7x             7x             7x    
import useSWR from 'swr';
import React from 'react';
import createFetcher from '@/helpers/createFetcher';
import { weatherSchema } from '../types/schemas';
import type { WeatherData } from '../types/schemas';
 
/**
 * SDD-L07: the local `WeatherData` declared here was the third copy of this shape, and the only one
 * that claimed `name`, `precipitation`, `humidity`, `windSpeed` and `grades` are always strings.
 * `/api/weather` answers with an explicit `null` in each of them for a city that geocodes but has no
 * current forecast, so the declaration was wrong for a case the route deliberately produces. The
 * shape now comes from the schema the response is checked against.
 */
const initialValues: WeatherData[] = [
    {
        city: 'moraƱa',
        name: 'Partly cloudy',
        precipitation: '0%',
        humidity: '50%',
        windSpeed: '10 km/h',
        grades: '15',
        imageUrl: '',
    },
];
 
const fetchWeather = createFetcher(weatherSchema, '/api/weather');
 
const useWeather = (
    cities: string[]
): {
    data: WeatherData[] | undefined;
    error: Error | undefined;
    loading: boolean;
} => {
    const url = React.useMemo(() => {
        const url = new URL(`${process.env.NEXT_PUBLIC_DOMAIN}/api/weather`);
        url.searchParams.append('cities', cities.join(','));
        return url;
    }, [cities]);
 
    const { data, error, isLoading } = useSWR<WeatherData[], Error>(url.toString(), fetchWeather, {
        dedupingInterval: 5000,
        keepPreviousData: true,
        fallback: initialValues,
        fallbackData: initialValues,
    });
 
    return {
        data,
        error,
        loading: isLoading,
    };
};
 
export default useWeather;
export type { WeatherData };