Skip to content

Commit c5b5263

Browse files
committed
add error tests
1 parent 2dd6d27 commit c5b5263

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
"scripts": {
4040
"start": "tsdx watch",
4141
"build": "tsdx build",
42-
"test": "tsdx --tsconfig ./tsconfig.test.json test --env=jsdom"
42+
"test": "tsdx test --env=jsdom"
4343
},
4444
"peerDependencies": {
4545
"react": ">=16.8"

test/useAsync.test.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,15 @@ describe('useAync', () => {
3333

3434
beforeEach(() => {
3535
fetch.resetMocks();
36-
37-
fetch.mockResponseOnce(JSON.stringify(fakeResults));
3836
});
3937

4038
it('should have a useAsync hook', () => {
4139
expect(useAsync).toBeDefined();
4240
});
4341

4442
it('should set loading flag when request is initially made', () => {
43+
fetch.mockResponseOnce(JSON.stringify(fakeResults));
44+
4545
const { result } = renderHook<
4646
StarwarsHeroArgs,
4747
UseAsyncReturn<StarwarsHero[]>
@@ -55,6 +55,8 @@ describe('useAync', () => {
5555
});
5656

5757
it('should resolve a successful request', async () => {
58+
fetch.mockResponseOnce(JSON.stringify(fakeResults));
59+
5860
const { result, waitForNextUpdate } = renderHook<
5961
StarwarsHeroArgs,
6062
UseAsyncReturn<StarwarsHero[]>
@@ -68,4 +70,22 @@ describe('useAync', () => {
6870
expect(result.current.loading).toBe(false);
6971
expect(result.current.error).toBeUndefined();
7072
});
73+
74+
it('should set error detail for unsuccessful request', async () => {
75+
fetch.mockReject(new Error('something went wrong'));
76+
77+
const { result, waitForNextUpdate } = renderHook<
78+
StarwarsHeroArgs,
79+
UseAsyncReturn<StarwarsHero[]>
80+
>(p => useAsync<StarwarsHero[], any>(p.asyncFunction, []), {
81+
initialProps: { ...props },
82+
});
83+
84+
await waitForNextUpdate();
85+
86+
expect(result.current.error).toBeDefined();
87+
expect(result.current.error!.message).toBe('something went wrong');
88+
expect(result.current.loading).toBe(false);
89+
expect(result.current.result).toBeUndefined();
90+
});
7191
});

0 commit comments

Comments
 (0)