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