简体   繁体   中英

how to write a unit test for a custom hook with a function inside of it

I'm a junior developer and I was assigned with a task--> to write a unit test for a custom hook. The custom hook is this:

const getQuote = (): string => funnyMessages[random(0, funnyMessages.length - 1)];
export const useQuote = () => {
    const [quote, setQuote] = useState<string>(getQuote());
   
    
    const refreshQuote = (): void => {
        const newQuote = getQuote();
        setQuote(newQuote);
    };
    return  [quote, refreshQuote] as const;

This is the test that I've tried to write but it doesn't work at all. So I need help from you.

 it('returns a random quote', () => {
    const getQuote = (): string => funnyMessages[random(0, funnyMessages.length - 1)];
    const { result } = renderHook(() => useQuote(getQuote()));

    expect(result.current.quote).toBe(getQuote);
   
    });

I think you should declare function getQuote as hook's parameter, not a global scope function.

Otherwise you can't simple mock this funciton.

Like this:

export const useQuote = (
  getQuote: () => string
) => {
    const [quote, setQuote] = useState<string>(getQuote());
   
    
    const refreshQuote = (): void => {
        const newQuote = getQuote();
        setQuote(newQuote);
    };
    return  [quote, refreshQuote] as const;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM