|
| 1 | +import {chain} from "../lib/chain"; |
| 2 | +import {fromCredentials} from "../lib/fromCredentials"; |
| 3 | +import {isCredentials} from "../lib/isCredentials"; |
| 4 | +import {CredentialError} from "../lib/CredentialError"; |
| 5 | + |
| 6 | +describe('chain', () => { |
| 7 | + it('should distill many credential providers into one', async () => { |
| 8 | + const provider = chain( |
| 9 | + fromCredentials({accessKeyId: 'foo', secretAccessKey: 'bar'}), |
| 10 | + fromCredentials({accessKeyId: 'baz', secretAccessKey: 'quux'}), |
| 11 | + ); |
| 12 | + |
| 13 | + expect(isCredentials(await provider())).toBe(true); |
| 14 | + }); |
| 15 | + |
| 16 | + it('should return the resolved value of the first successful promise', async () => { |
| 17 | + const creds = {accessKeyId: 'foo', secretAccessKey: 'bar'}; |
| 18 | + const provider = chain( |
| 19 | + () => Promise.reject(new CredentialError('Move along')), |
| 20 | + () => Promise.reject(new CredentialError('Nothing to see here')), |
| 21 | + fromCredentials(creds) |
| 22 | + ); |
| 23 | + |
| 24 | + expect(await provider()).toEqual(creds); |
| 25 | + }); |
| 26 | + |
| 27 | + it('should not invoke subsequent providers one resolves', async () => { |
| 28 | + const creds = {accessKeyId: 'foo', secretAccessKey: 'bar'}; |
| 29 | + const providers = [ |
| 30 | + jest.fn(() => Promise.reject(new CredentialError('Move along'))), |
| 31 | + jest.fn(() => Promise.resolve(creds)), |
| 32 | + jest.fn(() => fail('This provider should not be invoked')) |
| 33 | + ]; |
| 34 | + |
| 35 | + expect(await chain(...providers)()).toEqual(creds); |
| 36 | + expect(providers[0].mock.calls.length).toBe(1); |
| 37 | + expect(providers[1].mock.calls.length).toBe(1); |
| 38 | + expect(providers[2].mock.calls.length).toBe(0); |
| 39 | + }); |
| 40 | + |
| 41 | + it( |
| 42 | + 'should not invoke subsequent providers one is rejected with a terminal error', |
| 43 | + async () => { |
| 44 | + const providers = [ |
| 45 | + jest.fn(() => Promise.reject(new CredentialError('Move along'))), |
| 46 | + jest.fn(() => Promise.reject( |
| 47 | + new CredentialError('Stop here', false) |
| 48 | + )), |
| 49 | + jest.fn(() => fail('This provider should not be invoked')) |
| 50 | + ]; |
| 51 | + |
| 52 | + await chain(...providers)().then( |
| 53 | + () => { throw new Error('The promise should have been rejected'); }, |
| 54 | + err => { |
| 55 | + expect(err.message).toBe('Stop here'); |
| 56 | + expect(providers[0].mock.calls.length).toBe(1); |
| 57 | + expect(providers[1].mock.calls.length).toBe(1); |
| 58 | + expect(providers[2].mock.calls.length).toBe(0); |
| 59 | + } |
| 60 | + ); |
| 61 | + } |
| 62 | + ); |
| 63 | + |
| 64 | + it('should reject chains with no links', async () => { |
| 65 | + await chain()().then( |
| 66 | + () => { throw new Error('The promise should have been rejected'); }, |
| 67 | + () => { /* Promise rejected as expected */ } |
| 68 | + ); |
| 69 | + }); |
| 70 | +}); |
0 commit comments