16848: Fixes unit test.
[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 { Config, 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             clusterConfig: {
88                 Login: { LoginCluster: "" },
89             },
90         };
91
92         store.dispatch(initAuth(config));
93
94         store.subscribe(() => {
95             const auth = store.getState().auth;
96             if (auth.apiToken === "token" &&
97                 auth.sessions.length === 2 &&
98                 auth.sessions[0].status === 2 &&
99                 auth.sessions[1].status === 2
100             ) {
101                 try {
102                     expect(auth).toEqual({
103                         apiToken: "token",
104                         config: {
105                             apiRevision: 12345678,
106                             clusterConfig: {
107                                 Login: {
108                                     LoginCluster: "",
109                                 },
110                             },
111                             remoteHosts: {
112                                 "xc59z": "xc59z.arvadosapi.com",
113                             },
114                             rootUrl: "https://zzzzz.arvadosapi.com",
115                             uuidPrefix: "zzzzz",
116                         },
117                         sshKeys: [],
118                         extraApiToken: undefined,
119                         homeCluster: "zzzzz",
120                         localCluster: "zzzzz",
121                         loginCluster: undefined,
122                         remoteHostsConfig: {
123                             "zzzzz": {
124                                 "apiRevision": 12345678,
125                                 "clusterConfig": {
126                                     "Login": {
127                                         "LoginCluster": "",
128                                     },
129                                 },
130                                 "remoteHosts": {
131                                     "xc59z": "xc59z.arvadosapi.com",
132                                 },
133                                 "rootUrl": "https://zzzzz.arvadosapi.com",
134                                 "uuidPrefix": "zzzzz",
135                             },
136                             "xc59z": mockConfig({
137                                 apiRevision: 12345678,
138                                 baseUrl: "https://xc59z.arvadosapi.com/arvados/v1",
139                                 rootUrl: "https://xc59z.arvadosapi.com",
140                                 uuidPrefix: "xc59z"
141                             })
142                         },
143                         remoteHosts: {
144                             zzzzz: "zzzzz.arvadosapi.com",
145                             xc59z: "xc59z.arvadosapi.com"
146                         },
147                         sessions: [{
148                             "active": true,
149                             "baseUrl": undefined,
150                             "clusterId": "zzzzz",
151                             "email": "test@test.com",
152                             "loggedIn": true,
153                             "remoteHost": "https://zzzzz.arvadosapi.com",
154                             "status": 2,
155                             "token": "token",
156                             "name": "John Doe",
157                             "apiRevision": 12345678,
158                             "uuid": "zzzzz-tpzed-abcefg",
159                             "userIsActive": true
160                         }, {
161                             "active": false,
162                             "baseUrl": "",
163                             "clusterId": "xc59z",
164                             "email": "",
165                             "loggedIn": false,
166                             "remoteHost": "xc59z.arvadosapi.com",
167                             "status": 2,
168                             "token": "",
169                             "name": "",
170                             "uuid": "",
171                             "apiRevision": 0,
172                         }],
173                         user: {
174                             email: "test@test.com",
175                             firstName: "John",
176                             lastName: "Doe",
177                             uuid: "zzzzz-tpzed-abcefg",
178                             ownerUuid: "ownerUuid",
179                             username: "jdoe",
180                             prefs: { profile: {} },
181                             isAdmin: false,
182                             isActive: true
183                         }
184                     });
185                     done();
186                 } catch (e) {
187                     console.log(e);
188                 }
189             }
190         });
191     });
192
193
194     // TODO: Add remaining action tests
195     /*
196        it('should fire external url to login', () => {
197        const initialState = undefined;
198        window.location.assign = jest.fn();
199        reducer(initialState, authActions.LOGIN());
200        expect(window.location.assign).toBeCalledWith(
201        `/login?return_to=${window.location.protocol}//${window.location.host}/token`
202        );
203        });
204
205        it('should fire external url to logout', () => {
206        const initialState = undefined;
207        window.location.assign = jest.fn();
208        reducer(initialState, authActions.LOGOUT());
209        expect(window.location.assign).toBeCalledWith(
210        `/logout?return_to=${location.protocol}//${location.host}`
211        );
212        });
213      */
214 });