@websolutespa/bom-mixer-hooks 3.1.0 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,197 +1,197 @@
1
- import { render, screen, waitFor, waitForElementToBeRemoved } from '@testing-library/react';
2
- import { getLocalApiUrl } from '@websolutespa/bom-mixer-store';
3
- import { afterAll, beforeEach, describe, expect, test, vi } from 'vitest';
4
- import { useHttpDelete, useHttpFetch, useHttpGet, useHttpPatch, useHttpPost, useHttpPut } from './useHttp';
5
-
6
- const defaultResponse = {
7
- ok: true,
8
- status: 200,
9
- json: () => Promise.resolve(null),
10
- };
11
-
12
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
13
- function mockFetch(method: string = 'GET', result: any = { message: 'ok' }, overrideResponse: Partial<typeof defaultResponse> = {}, { manual = false } = {}) {
14
- const endpoint = '/endpoint';
15
- const url = `${getLocalApiUrl(endpoint)}?locale=en&market=ww`;
16
- const payload = { data: 'data' };
17
- const response = {
18
- ...defaultResponse,
19
- ...overrideResponse,
20
- json: () => Promise.resolve(result),
21
- } as Response;
22
- // resolve on a later tick, so the loading state is rendered, or when `resolve` is called with `manual`
23
- let resolveFetch: () => void = () => { };
24
- global.fetch = vi.fn(() =>
25
- new Promise<Response>((resolve) => {
26
- resolveFetch = () => resolve(response);
27
- if (!manual) {
28
- setTimeout(resolveFetch, 50);
29
- }
30
- })
31
- );
32
- const request: {
33
- body?: string;
34
- headers: { [key: string]: string },
35
- method: string;
36
- } = {
37
- headers: {
38
- 'Content-Type': 'application/json',
39
- },
40
- method,
41
- };
42
- if (['POST', 'PATCH', 'PUT'].includes(method)) {
43
- request.body = JSON.stringify(payload);
44
- }
45
- return { endpoint, url, payload, result, request, response, resolve: () => resolveFetch() };
46
- }
47
-
48
- describe('useHttp', () => {
49
- const ENV = process.env;
50
- const FETCH = global.fetch;
51
-
52
- beforeEach(() => {
53
- vi.resetModules();
54
- vi.resetAllMocks();
55
- vi.spyOn(console, 'error').mockImplementation(() => { });
56
- vi.spyOn(console, 'log').mockImplementation(() => { });
57
- process.env = {
58
- MIXER_SECRET: 'MIXER_SECRET_32_CHARS_LONG_12345',
59
- NEXT_PUBLIC_API: '/api',
60
- NEXT_PUBLIC_MOCK_FALLBACK_URL: 'http://localhost:3000',
61
- NEXT_PUBLIC_URL: 'http://localhost:3000',
62
- NODE_ENV: 'test',
63
- STORE_API_KEY: 'STORE_API_KEY',
64
- STORE_API: '/bowl/api',
65
- STORE_STRATEGY: 'mock',
66
- STORE_URL: 'http://localhost:4000',
67
- };
68
- });
69
-
70
- afterAll(() => {
71
- process.env = ENV;
72
- global.fetch = FETCH;
73
- });
74
-
75
- /*
76
- !!! todo
77
- test('useHttpFetch expect loading to be true', async () => {
78
- const mock = mockFetch();
79
- const { result } = renderHook(() => useHttpFetch(mock.url));
80
- await waitFor(() => expect(fetch).toBeCalled());
81
- expect(fetch).toHaveBeenCalledTimes(1);
82
- expect(fetch).toHaveBeenCalledWith(mock.url, mock.request);
83
- const [response, loading, error, setError] = result.current;
84
- expect(loading).toBe(true);
85
- });
86
- */
87
-
88
- test('useHttpFetch expect result ok', async () => {
89
- const mock = mockFetch('GET', undefined, undefined, { manual: true });
90
- const Wrapper = () => {
91
- const [response, loading, error, setError] = useHttpFetch(mock.url);
92
- return (
93
- <>
94
- {loading && <div data-testid="loading">loading</div>}
95
- {response && <div data-testid="result">{JSON.stringify(response)}</div>}
96
- {error && <div data-testid="error">{JSON.stringify(error)}</div>}
97
- </>
98
- );
99
- };
100
- const { findByTestId } = render(<Wrapper />);
101
- const loading = await findByTestId('loading');
102
- expect(loading).toHaveTextContent('loading');
103
- await waitFor(() => expect(fetch).toBeCalled());
104
- mock.resolve();
105
- await waitForElementToBeRemoved(() => screen.getByTestId('loading'));
106
- expect(fetch).toHaveBeenCalledTimes(1);
107
- expect(fetch).toHaveBeenCalledWith(mock.url, mock.request);
108
- const result = await waitFor(() => screen.getByTestId('result'));
109
- expect(result).toHaveTextContent(JSON.stringify(mock.result));
110
- });
111
-
112
- /*
113
- !!! todo
114
- test('useHttpFetch expect error', async () => {
115
- const mock = mockFetch(undefined, undefined, { ok: false, status: 500 });
116
- const Wrapper = () => {
117
- const [response, loading, error, setError] = useHttpFetch(mock.url);
118
- return (
119
- <>
120
- {loading && <div data-testid="loading">loading</div>}
121
- {response && <div data-testid="result">{JSON.stringify(response)}</div>}
122
- {error && <div data-testid="error">{JSON.stringify(error)}</div>}
123
- </>
124
- );
125
- };
126
- const { findByTestId } = render(<Wrapper />);
127
- const loading = await findByTestId('loading');
128
- expect(loading).toHaveTextContent('loading');
129
- await waitForElementToBeRemoved(() => screen.getByTestId('loading'));
130
- await waitFor(() => expect(fetch).toBeCalled());
131
- expect(fetch).toHaveBeenCalledTimes(1);
132
- expect(fetch).toHaveBeenCalledWith(mock.url, mock.request);
133
- const error = await waitFor(() => screen.getByTestId('error'));
134
- expect(error).toHaveTextContent('{"ok":false,"status":500}');
135
- });
136
- */
137
-
138
- test('useHttpGet expect result ok', TestMethod('GET'));
139
-
140
- test('useHttpPost expect result ok', TestMethod('POST'));
141
-
142
- test('useHttpPatch expect result ok', TestMethod('PATCH'));
143
-
144
- test('useHttpPut expect result ok', TestMethod('PUT'));
145
-
146
- test('useHttpDelete expect result ok', TestMethod('DELETE'));
147
-
148
- function TestMethod(method?: string) {
149
- const useHook = (mock: ReturnType<typeof mockFetch>) => {
150
- switch (method) {
151
- case 'GET':
152
- // eslint-disable-next-line react-hooks/rules-of-hooks
153
- return useHttpGet(mock.url);
154
- case 'POST':
155
- // eslint-disable-next-line react-hooks/rules-of-hooks
156
- return useHttpPost(mock.url, mock.payload);
157
- case 'PATCH':
158
- // eslint-disable-next-line react-hooks/rules-of-hooks
159
- return useHttpPatch(mock.url, mock.payload);
160
- case 'PUT':
161
- // eslint-disable-next-line react-hooks/rules-of-hooks
162
- return useHttpPut(mock.url, mock.payload);
163
- case 'DELETE':
164
- // eslint-disable-next-line react-hooks/rules-of-hooks
165
- return useHttpDelete(mock.url);
166
- default:
167
- // eslint-disable-next-line react-hooks/rules-of-hooks
168
- return useHttpFetch(mock.url);
169
- }
170
- };
171
- return async () => {
172
- const mock = mockFetch(method, undefined, undefined, { manual: true });
173
- const Wrapper = () => {
174
- const [response, loading, error, setError] = useHook(mock);
175
- return (
176
- <>
177
- {loading && <div data-testid="loading">loading</div>}
178
- {response && <div data-testid="result">{JSON.stringify(response)}</div>}
179
- {error && <div data-testid="error">{JSON.stringify(error)}</div>}
180
- </>
181
- );
182
- };
183
- const { findByTestId } = render(<Wrapper />);
184
- const loading = await findByTestId('loading');
185
- expect(loading).toHaveTextContent('loading');
186
- await waitFor(() => expect(fetch).toBeCalled());
187
- mock.resolve();
188
- await waitForElementToBeRemoved(() => screen.getByTestId('loading'));
189
- expect(fetch).toHaveBeenCalledTimes(1);
190
- expect(fetch).toHaveBeenCalledWith(mock.url, mock.request);
191
- const result = await waitFor(() => screen.getByTestId('result'));
192
- expect(result).toHaveTextContent(JSON.stringify(mock.result));
193
- };
194
- }
195
-
196
- });
197
-
1
+ import { render, screen, waitFor, waitForElementToBeRemoved } from '@testing-library/react';
2
+ import { getLocalApiUrl } from '@websolutespa/bom-mixer-store';
3
+ import { afterAll, beforeEach, describe, expect, test, vi } from 'vitest';
4
+ import { useHttpDelete, useHttpFetch, useHttpGet, useHttpPatch, useHttpPost, useHttpPut } from './useHttp';
5
+
6
+ const defaultResponse = {
7
+ ok: true,
8
+ status: 200,
9
+ json: () => Promise.resolve(null),
10
+ };
11
+
12
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
13
+ function mockFetch(method: string = 'GET', result: any = { message: 'ok' }, overrideResponse: Partial<typeof defaultResponse> = {}, { manual = false } = {}) {
14
+ const endpoint = '/endpoint';
15
+ const url = `${getLocalApiUrl(endpoint)}?locale=en&market=ww`;
16
+ const payload = { data: 'data' };
17
+ const response = {
18
+ ...defaultResponse,
19
+ ...overrideResponse,
20
+ json: () => Promise.resolve(result),
21
+ } as Response;
22
+ // resolve on a later tick, so the loading state is rendered, or when `resolve` is called with `manual`
23
+ let resolveFetch: () => void = () => { };
24
+ global.fetch = vi.fn(() =>
25
+ new Promise<Response>((resolve) => {
26
+ resolveFetch = () => resolve(response);
27
+ if (!manual) {
28
+ setTimeout(resolveFetch, 50);
29
+ }
30
+ })
31
+ );
32
+ const request: {
33
+ body?: string;
34
+ headers: { [key: string]: string },
35
+ method: string;
36
+ } = {
37
+ headers: {
38
+ 'Content-Type': 'application/json',
39
+ },
40
+ method,
41
+ };
42
+ if (['POST', 'PATCH', 'PUT'].includes(method)) {
43
+ request.body = JSON.stringify(payload);
44
+ }
45
+ return { endpoint, url, payload, result, request, response, resolve: () => resolveFetch() };
46
+ }
47
+
48
+ describe('useHttp', () => {
49
+ const ENV = process.env;
50
+ const FETCH = global.fetch;
51
+
52
+ beforeEach(() => {
53
+ vi.resetModules();
54
+ vi.resetAllMocks();
55
+ vi.spyOn(console, 'error').mockImplementation(() => { });
56
+ vi.spyOn(console, 'log').mockImplementation(() => { });
57
+ process.env = {
58
+ MIXER_SECRET: 'MIXER_SECRET_32_CHARS_LONG_12345',
59
+ NEXT_PUBLIC_API: '/api',
60
+ NEXT_PUBLIC_MOCK_FALLBACK_URL: 'http://localhost:3000',
61
+ NEXT_PUBLIC_URL: 'http://localhost:3000',
62
+ NODE_ENV: 'test',
63
+ STORE_API_KEY: 'STORE_API_KEY',
64
+ STORE_API: '/bowl/api',
65
+ STORE_STRATEGY: 'mock',
66
+ STORE_URL: 'http://localhost:4000',
67
+ };
68
+ });
69
+
70
+ afterAll(() => {
71
+ process.env = ENV;
72
+ global.fetch = FETCH;
73
+ });
74
+
75
+ /*
76
+ !!! todo
77
+ test('useHttpFetch expect loading to be true', async () => {
78
+ const mock = mockFetch();
79
+ const { result } = renderHook(() => useHttpFetch(mock.url));
80
+ await waitFor(() => expect(fetch).toBeCalled());
81
+ expect(fetch).toHaveBeenCalledTimes(1);
82
+ expect(fetch).toHaveBeenCalledWith(mock.url, mock.request);
83
+ const [response, loading, error, setError] = result.current;
84
+ expect(loading).toBe(true);
85
+ });
86
+ */
87
+
88
+ test('useHttpFetch expect result ok', async () => {
89
+ const mock = mockFetch('GET', undefined, undefined, { manual: true });
90
+ const Wrapper = () => {
91
+ const [response, loading, error, setError] = useHttpFetch(mock.url);
92
+ return (
93
+ <>
94
+ {loading && <div data-testid="loading">loading</div>}
95
+ {response && <div data-testid="result">{JSON.stringify(response)}</div>}
96
+ {error && <div data-testid="error">{JSON.stringify(error)}</div>}
97
+ </>
98
+ );
99
+ };
100
+ const { findByTestId } = render(<Wrapper />);
101
+ const loading = await findByTestId('loading');
102
+ expect(loading).toHaveTextContent('loading');
103
+ await waitFor(() => expect(fetch).toBeCalled());
104
+ mock.resolve();
105
+ await waitForElementToBeRemoved(() => screen.getByTestId('loading'));
106
+ expect(fetch).toHaveBeenCalledTimes(1);
107
+ expect(fetch).toHaveBeenCalledWith(mock.url, mock.request);
108
+ const result = await waitFor(() => screen.getByTestId('result'));
109
+ expect(result).toHaveTextContent(JSON.stringify(mock.result));
110
+ });
111
+
112
+ /*
113
+ !!! todo
114
+ test('useHttpFetch expect error', async () => {
115
+ const mock = mockFetch(undefined, undefined, { ok: false, status: 500 });
116
+ const Wrapper = () => {
117
+ const [response, loading, error, setError] = useHttpFetch(mock.url);
118
+ return (
119
+ <>
120
+ {loading && <div data-testid="loading">loading</div>}
121
+ {response && <div data-testid="result">{JSON.stringify(response)}</div>}
122
+ {error && <div data-testid="error">{JSON.stringify(error)}</div>}
123
+ </>
124
+ );
125
+ };
126
+ const { findByTestId } = render(<Wrapper />);
127
+ const loading = await findByTestId('loading');
128
+ expect(loading).toHaveTextContent('loading');
129
+ await waitForElementToBeRemoved(() => screen.getByTestId('loading'));
130
+ await waitFor(() => expect(fetch).toBeCalled());
131
+ expect(fetch).toHaveBeenCalledTimes(1);
132
+ expect(fetch).toHaveBeenCalledWith(mock.url, mock.request);
133
+ const error = await waitFor(() => screen.getByTestId('error'));
134
+ expect(error).toHaveTextContent('{"ok":false,"status":500}');
135
+ });
136
+ */
137
+
138
+ test('useHttpGet expect result ok', TestMethod('GET'));
139
+
140
+ test('useHttpPost expect result ok', TestMethod('POST'));
141
+
142
+ test('useHttpPatch expect result ok', TestMethod('PATCH'));
143
+
144
+ test('useHttpPut expect result ok', TestMethod('PUT'));
145
+
146
+ test('useHttpDelete expect result ok', TestMethod('DELETE'));
147
+
148
+ function TestMethod(method?: string) {
149
+ const useHook = (mock: ReturnType<typeof mockFetch>) => {
150
+ switch (method) {
151
+ case 'GET':
152
+ // eslint-disable-next-line react-hooks/rules-of-hooks
153
+ return useHttpGet(mock.url);
154
+ case 'POST':
155
+ // eslint-disable-next-line react-hooks/rules-of-hooks
156
+ return useHttpPost(mock.url, mock.payload);
157
+ case 'PATCH':
158
+ // eslint-disable-next-line react-hooks/rules-of-hooks
159
+ return useHttpPatch(mock.url, mock.payload);
160
+ case 'PUT':
161
+ // eslint-disable-next-line react-hooks/rules-of-hooks
162
+ return useHttpPut(mock.url, mock.payload);
163
+ case 'DELETE':
164
+ // eslint-disable-next-line react-hooks/rules-of-hooks
165
+ return useHttpDelete(mock.url);
166
+ default:
167
+ // eslint-disable-next-line react-hooks/rules-of-hooks
168
+ return useHttpFetch(mock.url);
169
+ }
170
+ };
171
+ return async () => {
172
+ const mock = mockFetch(method, undefined, undefined, { manual: true });
173
+ const Wrapper = () => {
174
+ const [response, loading, error, setError] = useHook(mock);
175
+ return (
176
+ <>
177
+ {loading && <div data-testid="loading">loading</div>}
178
+ {response && <div data-testid="result">{JSON.stringify(response)}</div>}
179
+ {error && <div data-testid="error">{JSON.stringify(error)}</div>}
180
+ </>
181
+ );
182
+ };
183
+ const { findByTestId } = render(<Wrapper />);
184
+ const loading = await findByTestId('loading');
185
+ expect(loading).toHaveTextContent('loading');
186
+ await waitFor(() => expect(fetch).toBeCalled());
187
+ mock.resolve();
188
+ await waitForElementToBeRemoved(() => screen.getByTestId('loading'));
189
+ expect(fetch).toHaveBeenCalledTimes(1);
190
+ expect(fetch).toHaveBeenCalledWith(mock.url, mock.request);
191
+ const result = await waitFor(() => screen.getByTestId('result'));
192
+ expect(result).toHaveTextContent(JSON.stringify(mock.result));
193
+ };
194
+ }
195
+
196
+ });
197
+
@@ -1,79 +1,79 @@
1
- import { act, renderHook } from '@testing-library/react';
2
- import { describe, expect, test } from 'vitest';
3
- import { usePagination } from './usePagination';
4
-
5
- describe('usePagination', () => {
6
-
7
- test('should paginate items', () => {
8
- const items = new Array(100).fill(0).map((_, i) => i + 1);
9
- const { result } = renderHook(() => usePagination(items));
10
- expect(result.current.page).toEqual(1);
11
- expect(result.current.pages).toEqual(9);
12
- expect(result.current.total).toEqual(100);
13
- expect(result.current.items.length).toEqual(12);
14
- expect(result.current.items[0]).toEqual(1);
15
- });
16
-
17
- test('should paginate items with params', () => {
18
- const items = new Array(100).fill(0).map((_, i) => i + 1);
19
- const { result } = renderHook(() => usePagination(items, {
20
- page: 2,
21
- perPage: 10,
22
- }));
23
- expect(result.current.page).toEqual(2);
24
- expect(result.current.pages).toEqual(10);
25
- expect(result.current.total).toEqual(100);
26
- expect(result.current.items.length).toEqual(10);
27
- expect(result.current.items[0]).toEqual(11);
28
- });
29
-
30
- test('should call nextPage and paginate items', async () => {
31
- const items = new Array(100).fill(0).map((_, i) => i + 1);
32
- const { result } = renderHook(() => usePagination(items, {
33
- page: 2,
34
- perPage: 10,
35
- }));
36
- act(() => { result.current.goToNextPage(); });
37
- expect(result.current.page).toEqual(3);
38
- expect(result.current.items.length).toEqual(10);
39
- expect(result.current.items[0]).toEqual(21);
40
- });
41
-
42
- test('should call previousPage and paginate items', async () => {
43
- const items = new Array(100).fill(0).map((_, i) => i + 1);
44
- const { result } = renderHook(() => usePagination(items, {
45
- page: 2,
46
- perPage: 10,
47
- }));
48
- act(() => { result.current.goToPreviousPage(); });
49
- expect(result.current.page).toEqual(1);
50
- expect(result.current.items.length).toEqual(10);
51
- expect(result.current.items[0]).toEqual(1);
52
- });
53
-
54
- test('should call goToPage and paginate items', async () => {
55
- const items = new Array(100).fill(0).map((_, i) => i + 1);
56
- const { result } = renderHook(() => usePagination(items, {
57
- page: 2,
58
- perPage: 10,
59
- }));
60
- act(() => { result.current.goToPage(4); });
61
- expect(result.current.page).toEqual(4);
62
- expect(result.current.items.length).toEqual(10);
63
- expect(result.current.items[0]).toEqual(31);
64
- });
65
-
66
- test('should call setPerPage and paginate items', async () => {
67
- const items = new Array(100).fill(0).map((_, i) => i + 1);
68
- const { result } = renderHook(() => usePagination(items, {
69
- page: 2,
70
- perPage: 10,
71
- }));
72
- act(() => { result.current.setPerPage(20); });
73
- expect(result.current.pages).toEqual(5);
74
- expect(result.current.page).toEqual(2);
75
- expect(result.current.items.length).toEqual(20);
76
- expect(result.current.items[0]).toEqual(21);
77
- });
78
-
79
- });
1
+ import { act, renderHook } from '@testing-library/react';
2
+ import { describe, expect, test } from 'vitest';
3
+ import { usePagination } from './usePagination';
4
+
5
+ describe('usePagination', () => {
6
+
7
+ test('should paginate items', () => {
8
+ const items = new Array(100).fill(0).map((_, i) => i + 1);
9
+ const { result } = renderHook(() => usePagination(items));
10
+ expect(result.current.page).toEqual(1);
11
+ expect(result.current.pages).toEqual(9);
12
+ expect(result.current.total).toEqual(100);
13
+ expect(result.current.items.length).toEqual(12);
14
+ expect(result.current.items[0]).toEqual(1);
15
+ });
16
+
17
+ test('should paginate items with params', () => {
18
+ const items = new Array(100).fill(0).map((_, i) => i + 1);
19
+ const { result } = renderHook(() => usePagination(items, {
20
+ page: 2,
21
+ perPage: 10,
22
+ }));
23
+ expect(result.current.page).toEqual(2);
24
+ expect(result.current.pages).toEqual(10);
25
+ expect(result.current.total).toEqual(100);
26
+ expect(result.current.items.length).toEqual(10);
27
+ expect(result.current.items[0]).toEqual(11);
28
+ });
29
+
30
+ test('should call nextPage and paginate items', async () => {
31
+ const items = new Array(100).fill(0).map((_, i) => i + 1);
32
+ const { result } = renderHook(() => usePagination(items, {
33
+ page: 2,
34
+ perPage: 10,
35
+ }));
36
+ act(() => { result.current.goToNextPage(); });
37
+ expect(result.current.page).toEqual(3);
38
+ expect(result.current.items.length).toEqual(10);
39
+ expect(result.current.items[0]).toEqual(21);
40
+ });
41
+
42
+ test('should call previousPage and paginate items', async () => {
43
+ const items = new Array(100).fill(0).map((_, i) => i + 1);
44
+ const { result } = renderHook(() => usePagination(items, {
45
+ page: 2,
46
+ perPage: 10,
47
+ }));
48
+ act(() => { result.current.goToPreviousPage(); });
49
+ expect(result.current.page).toEqual(1);
50
+ expect(result.current.items.length).toEqual(10);
51
+ expect(result.current.items[0]).toEqual(1);
52
+ });
53
+
54
+ test('should call goToPage and paginate items', async () => {
55
+ const items = new Array(100).fill(0).map((_, i) => i + 1);
56
+ const { result } = renderHook(() => usePagination(items, {
57
+ page: 2,
58
+ perPage: 10,
59
+ }));
60
+ act(() => { result.current.goToPage(4); });
61
+ expect(result.current.page).toEqual(4);
62
+ expect(result.current.items.length).toEqual(10);
63
+ expect(result.current.items[0]).toEqual(31);
64
+ });
65
+
66
+ test('should call setPerPage and paginate items', async () => {
67
+ const items = new Array(100).fill(0).map((_, i) => i + 1);
68
+ const { result } = renderHook(() => usePagination(items, {
69
+ page: 2,
70
+ perPage: 10,
71
+ }));
72
+ act(() => { result.current.setPerPage(20); });
73
+ expect(result.current.pages).toEqual(5);
74
+ expect(result.current.page).toEqual(2);
75
+ expect(result.current.items.length).toEqual(20);
76
+ expect(result.current.items[0]).toEqual(21);
77
+ });
78
+
79
+ });
@@ -1,4 +1,4 @@
1
- import { describe, expect, test } from 'vitest';
1
+ import { describe, expect, test } from 'vitest';
2
2
  // readme https://testing-library.com/
3
3
  import { act, renderHook } from '@testing-library/react';
4
4
  import { usePaginationLegacy } from './usePaginationLegacy';