|
| 1 | +import { grpc } from '@improbable-eng/grpc-web'; |
| 2 | +import AppStorage from 'util/appStorage'; |
| 3 | +import { AuthStore, createStore, Store } from 'store'; |
| 4 | +import { PersistentSettings } from 'store/stores/settingsStore'; |
| 5 | + |
| 6 | +const grpcMock = grpc as jest.Mocked<typeof grpc>; |
| 7 | +const appStorageMock = AppStorage as jest.Mock<AppStorage<PersistentSettings>>; |
| 8 | + |
| 9 | +describe('AuthStore', () => { |
| 10 | + let rootStore: Store; |
| 11 | + let store: AuthStore; |
| 12 | + |
| 13 | + beforeEach(() => { |
| 14 | + rootStore = createStore(); |
| 15 | + store = rootStore.authStore; |
| 16 | + }); |
| 17 | + |
| 18 | + it('should set credentials', () => { |
| 19 | + expect(store.credentials).toBe(''); |
| 20 | + store.setCredentials('test'); |
| 21 | + expect(store.credentials).toEqual('test'); |
| 22 | + store.setCredentials(''); |
| 23 | + expect(store.credentials).toEqual(''); |
| 24 | + }); |
| 25 | + |
| 26 | + it('should login successfully', async () => { |
| 27 | + await store.login('test-pw'); |
| 28 | + expect(store.credentials).toBe('dGVzdC1wdzp0ZXN0LXB3'); |
| 29 | + }); |
| 30 | + |
| 31 | + it('should fail to login with a blank password', async () => { |
| 32 | + await expect(store.login('')).rejects.toThrow('oops, password is required'); |
| 33 | + expect(store.credentials).toBe(''); |
| 34 | + }); |
| 35 | + |
| 36 | + it('should fail to login with an invalid password', async () => { |
| 37 | + grpcMock.unary.mockImplementationOnce(desc => { |
| 38 | + if (desc.methodName === 'GetInfo') throw new Error('test-err'); |
| 39 | + return undefined as any; |
| 40 | + }); |
| 41 | + await expect(store.login('test-pw')).rejects.toThrow( |
| 42 | + 'oops, that password is incorrect', |
| 43 | + ); |
| 44 | + expect(store.credentials).toBe(''); |
| 45 | + }); |
| 46 | + |
| 47 | + it('should load credentials from session storage', async () => { |
| 48 | + const getMock = appStorageMock.mock.instances[0].getSession as jest.Mock; |
| 49 | + getMock.mockReturnValue('test-creds'); |
| 50 | + await store.init(); |
| 51 | + expect(store.credentials).toBe('test-creds'); |
| 52 | + }); |
| 53 | + |
| 54 | + it('should not store invalid credentials from session storage', async () => { |
| 55 | + grpcMock.unary.mockImplementationOnce((desc, opts) => { |
| 56 | + if (desc.methodName === 'GetInfo') { |
| 57 | + opts.onEnd({ |
| 58 | + status: grpc.Code.Unauthenticated, |
| 59 | + } as any); |
| 60 | + } |
| 61 | + return undefined as any; |
| 62 | + }); |
| 63 | + const getMock = appStorageMock.mock.instances[0].getSession as jest.Mock; |
| 64 | + getMock.mockReturnValue('test-creds'); |
| 65 | + await store.init(); |
| 66 | + expect(store.credentials).toBe(''); |
| 67 | + }); |
| 68 | +}); |
0 commit comments