16848: Improved event handler installation/removal.
[arvados-workbench2.git] / src / store / auth / auth-action.test.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { initAuth } from "./auth-action";
6 import { API_TOKEN_KEY } from "~/services/auth-service/auth-service";
7
8 import 'jest-localstorage-mock';
9 import { ServiceRepository, createServices } from "~/services/services";
10 import { configureStore, RootStore } from "../store";
11 import { createBrowserHistory } from "history";
12 import { mockConfig } from '~/common/config';
13 import { ApiActions } from "~/services/api/api-actions";
14 import { ACCOUNT_LINK_STATUS_KEY } from '~/services/link-account-service/link-account-service';
15 import Axios from "axios";
16 import MockAdapter from "axios-mock-adapter";
17 import { ImportMock } from 'ts-mock-imports';
18 import * as servicesModule from "~/services/services";
19
20 describe('auth-actions', () => {
21     const axiosInst = Axios.create({ headers: {} });
22     const axiosMock = new MockAdapter(axiosInst);
23
24     let store: RootStore;
25     let services: ServiceRepository;
26     const config: any = {};
27     const actions: ApiActions = {
28         progressFn: (id: string, working: boolean) => { },
29         errorFn: (id: string, message: string) => { }
30     };
31     let importMocks: any[];
32
33     beforeEach(() => {
34         axiosMock.reset();
35         services = createServices(mockConfig({}), actions, axiosInst);
36         store = configureStore(createBrowserHistory(), services, config);
37         localStorage.clear();
38         importMocks = [];
39     });
40
41     afterEach(() => {
42         importMocks.map(m => m.restore());
43     });
44
45     it('should initialise state with user and api token from local storage', (done) => {
46
47         axiosMock
48             .onGet("/users/current")
49             .reply(200, {
50                 email: "test@test.com",
51                 first_name: "John",
52                 last_name: "Doe",
53                 uuid: "zzzzz-tpzed-abcefg",
54                 owner_uuid: "ownerUuid",
55                 is_admin: false,
56                 is_active: true,
57                 username: "jdoe",
58                 prefs: {}
59             });
60
61         axiosMock
62             .onGet("https://xc59z.arvadosapi.com/discovery/v1/apis/arvados/v1/rest")
63             .reply(200, {
64                 baseUrl: "https://xc59z.arvadosapi.com/arvados/v1",
65                 keepWebServiceUrl: "",
66                 keepWebInlineServiceUrl: "",
67                 remoteHosts: {},
68                 rootUrl: "https://xc59z.arvadosapi.com",
69                 uuidPrefix: "xc59z",
70                 websocketUrl: "",
71                 workbenchUrl: "",
72                 workbench2Url: "",
73                 revision: 12345678
74             });
75
76         importMocks.push(ImportMock.mockFunction(servicesModule, 'createServices', services));
77
78         // Only test the case when a link account operation is not being cancelled
79         sessionStorage.setItem(ACCOUNT_LINK_STATUS_KEY, "0");
80         localStorage.setItem(API_TOKEN_KEY, "token");
81
82         const config: any = {
83             rootUrl: "https://zzzzz.arvadosapi.com",
84             uuidPrefix: "zzzzz",
85             remoteHosts: { xc59z: "xc59z.arvadosapi.com" },
86             apiRevision: 12345678,
87         };
88
89         store.dispatch(initAuth(config));
90
91         store.subscribe(() => {
92             const auth = store.getState().auth;
93             if (auth.apiToken === "token" &&
94                 auth.sessions.length === 2 &&
95                 auth.sessions[0].status === 2 &&
96                 auth.sessions[1].status === 2
97             ) {
98                 try {
99                     expect(auth).toEqual({
100                         apiToken: "token",
101                         config: {
102                             apiRevision: 12345678,
103                             remoteHosts: {
104                                 "xc59z": "xc59z.arvadosapi.com",
105                             },
106                             rootUrl: "https://zzzzz.arvadosapi.com",
107                             uuidPrefix: "zzzzz",
108                         },
109                         sshKeys: [],
110                         homeCluster: "zzzzz",
111                         localCluster: "zzzzz",
112                         loginCluster: undefined,
113                         remoteHostsConfig: {
114                             "zzzzz": {
115                                 "apiRevision": 12345678,
116                                 "remoteHosts": {
117                                     "xc59z": "xc59z.arvadosapi.com",
118                                 },
119                                 "rootUrl": "https://zzzzz.arvadosapi.com",
120                                 "uuidPrefix": "zzzzz",
121                             },
122                             "xc59z": mockConfig({
123                                 apiRevision: 12345678,
124                                 baseUrl: "https://xc59z.arvadosapi.com/arvados/v1",
125                                 rootUrl: "https://xc59z.arvadosapi.com",
126                                 uuidPrefix: "xc59z"
127                             })
128                         },
129                         remoteHosts: {
130                             zzzzz: "zzzzz.arvadosapi.com",
131                             xc59z: "xc59z.arvadosapi.com"
132                         },
133                         sessions: [{
134                             "active": true,
135                             "baseUrl": undefined,
136                             "clusterId": "zzzzz",
137                             "email": "test@test.com",
138                             "loggedIn": true,
139                             "remoteHost": "https://zzzzz.arvadosapi.com",
140                             "status": 2,
141                             "token": "token",
142                             "name": "John Doe",
143                             "apiRevision": 12345678,
144                             "uuid": "zzzzz-tpzed-abcefg",
145                             "userIsActive": true
146                         }, {
147                             "active": false,
148                             "baseUrl": "",
149                             "clusterId": "xc59z",
150                             "email": "",
151                             "loggedIn": false,
152                             "remoteHost": "xc59z.arvadosapi.com",
153                             "status": 2,
154                             "token": "",
155                             "name": "",
156                             "uuid": "",
157                             "apiRevision": 0,
158                         }],
159                         user: {
160                             email: "test@test.com",
161                             firstName: "John",
162                             lastName: "Doe",
163                             uuid: "zzzzz-tpzed-abcefg",
164                             ownerUuid: "ownerUuid",
165                             username: "jdoe",
166                             prefs: { profile: {} },
167                             isAdmin: false,
168                             isActive: true
169                         }
170                     });
171                     done();
172                 } catch (e) {
173                     console.log(e);
174                 }
175             }
176         });
177     });
178
179
180     // TODO: Add remaining action tests
181     /*
182        it('should fire external url to login', () => {
183        const initialState = undefined;
184        window.location.assign = jest.fn();
185        reducer(initialState, authActions.LOGIN());
186        expect(window.location.assign).toBeCalledWith(
187        `/login?return_to=${window.location.protocol}//${window.location.host}/token`
188        );
189        });
190
191        it('should fire external url to logout', () => {
192        const initialState = undefined;
193        window.location.assign = jest.fn();
194        reducer(initialState, authActions.LOGOUT());
195        expect(window.location.assign).toBeCalledWith(
196        `/logout?return_to=${location.protocol}//${location.host}`
197        );
198        });
199      */
200 });