|
1 | | -import { asyncMap, wait } from '../src/async'; |
| 1 | +import { asyncMap, safeAwait, wait } from '../src/async'; |
2 | 2 |
|
3 | 3 | test('wait', () => { |
4 | 4 | return new Promise(done => { |
@@ -40,3 +40,46 @@ test('asyncMap 并发', async () => { |
40 | 40 | ); |
41 | 41 | expect(fn).toBeCalled(); |
42 | 42 | }); |
| 43 | + |
| 44 | +describe('Await safeAwait test', () => { |
| 45 | + test('should return a value when resolved', async () => { |
| 46 | + const testInput = 41; |
| 47 | + const promise = Promise.resolve(testInput); |
| 48 | + |
| 49 | + const [err, data] = await safeAwait<number>(promise); |
| 50 | + |
| 51 | + expect(err).toBeNull(); |
| 52 | + expect(data).toEqual(testInput); |
| 53 | + }); |
| 54 | + |
| 55 | + test('should return an error when promise is rejected', async () => { |
| 56 | + const testInput = 41; |
| 57 | + const promise = Promise.reject('Error'); |
| 58 | + |
| 59 | + const [err, data] = await safeAwait<number>(promise); |
| 60 | + |
| 61 | + expect(err).toEqual('Error'); |
| 62 | + expect(data).toBeUndefined(); |
| 63 | + }); |
| 64 | + |
| 65 | + test('should add external properties safeAwait the error object', async () => { |
| 66 | + const promise = Promise.reject({ error: 'Error message' }); |
| 67 | + |
| 68 | + const [err] = await safeAwait<string, { error: string; extraKey: number }>(promise, { |
| 69 | + extraKey: 1 |
| 70 | + }); |
| 71 | + |
| 72 | + expect(err).toBeTruthy(); |
| 73 | + expect((err as any).extraKey).toEqual(1); |
| 74 | + expect((err as any).error).toEqual('Error message'); |
| 75 | + }); |
| 76 | + |
| 77 | + test('should receive the type of the parent if no type was passed', async () => { |
| 78 | + let user: { name: string }; |
| 79 | + let err: Error; |
| 80 | + // @ts-ignore |
| 81 | + [err, user] = await safeAwait(Promise.resolve({ name: '123' }));// eslint-disable-line |
| 82 | + |
| 83 | + expect(user.name).toEqual('123'); |
| 84 | + }); |
| 85 | +}); |
0 commit comments