Skip to content

Commit

Permalink
test http hook
Browse files Browse the repository at this point in the history
  • Loading branch information
jwkaterina committed Apr 25, 2024
1 parent 984c38c commit 05f3793
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 18 deletions.
71 changes: 71 additions & 0 deletions src/app/hooks/http-hook.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { renderHook } from '@testing-library/react';
import '@testing-library/jest-dom';
import { useHttpClient } from './http-hook';
import { StatusContext } from '../context/status-context';
import { StatusType } from '../types/types';
import BackendError from '../error/backend-error';

describe('http-hook', () => {

it('should render hook with resolved fetch and loading', async() => {

global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({message: 'ok'})
});

const status = {
isLoading: false,
setIsLoading: jest.fn(),
status: StatusType.SUCCESS,
setStatus: jest.fn(),
message: null,
setMessage: jest.fn()
};
const { result } = renderHook(() => useHttpClient(), {
wrapper: ({ children }) => <StatusContext.Provider value={status}>{children}</StatusContext.Provider>,
});

const sendRequest = result.current.sendRequest;
await sendRequest(
`/recipes`, 'GET', null, {
Authorization: 'Bearer ' + 'token'
}, true, true
);
expect(status.setIsLoading).toHaveBeenNthCalledWith(1, true);
expect(status.setIsLoading).toHaveBeenNthCalledWith(2, false);
expect(status.setStatus).toHaveBeenCalledWith(StatusType.SUCCESS);
})

it('should render hook with error', async() => {

global.fetch = jest.fn().mockResolvedValue({
ok: false,
json: () => Promise.resolve({message: 'Backend error'})
});

const status = {
isLoading: false,
setIsLoading: jest.fn(),
status: StatusType.SUCCESS,
setStatus: jest.fn(),
message: null,
setMessage: jest.fn()
};
const { result } = renderHook(() => useHttpClient(), {
wrapper: ({ children }) => <StatusContext.Provider value={status}>{children}</StatusContext.Provider>,
});

const sendRequest = result.current.sendRequest;
await expect(sendRequest(
`/recipes`, 'GET', null, {
Authorization: 'Bearer ' + 'token'
}, true, true
)).rejects.toThrow(BackendError);
expect(status.setIsLoading).toHaveBeenNthCalledWith(1, true);
expect(status.setIsLoading).toHaveBeenNthCalledWith(2, false);
expect(status.setStatus).toHaveBeenCalledWith(StatusType.ERROR);
expect(status.setMessage).toHaveBeenCalledWith('Backend error');
})

})
19 changes: 1 addition & 18 deletions src/app/hooks/http-hook.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,23 @@
import { useCallback, useRef, useEffect, useContext } from 'react';
import { useCallback, useContext } from 'react';
import { StatusContext } from '../context/status-context';
import { StatusType } from '../types/types';
import BackendError from '../error/backend-error';

export const useHttpClient = () => {
const { setIsLoading, setStatus, setMessage } = useContext(StatusContext);

// const activeHttpRequests = useRef<AbortController[]>([]);

const sendRequest = useCallback(
async (url: string, method: string = 'GET', body: null | string | FormData = null, headers = {}, isLoading: boolean = true, setStatusSuccess: boolean = true): Promise<any> => {
if(isLoading == true) setIsLoading(true);
// const httpAbortCtrl = new AbortController();
// activeHttpRequests.current.push(httpAbortCtrl);

try {
const response = await fetch(url, {
method,
body,
headers,
// signal: httpAbortCtrl.signal
});

const responseData = await response.json();

// activeHttpRequests.current = activeHttpRequests.current.filter(
// reqCtrl => reqCtrl !== httpAbortCtrl
// );

if (!response.ok) {
throw new BackendError(responseData.message);
}
Expand All @@ -48,12 +38,5 @@ export const useHttpClient = () => {
}
},[]);

// useEffect(() => {
// return () => {
// // eslint-disable-next-line react-hooks/exhaustive-deps
// activeHttpRequests.current.forEach(abortCtrl => abortCtrl.abort());
// };
// }, []);

return { sendRequest };
}

0 comments on commit 05f3793

Please sign in to comment.