3d60c4f400fb1c0fb6ee8f10e4e11a1327d00eb3
[arvados-workbench2.git] / src / store / auth / auth-reducer.test.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import authReducer from "./auth-reducer";
6 import actions from "./auth-action";
7 import {
8     API_TOKEN_KEY,
9     USER_EMAIL_KEY,
10     USER_FIRST_NAME_KEY,
11     USER_LAST_NAME_KEY
12 } from "../../services/auth-service/auth-service";
13
14 require('jest-localstorage-mock');
15
16 describe('auth-reducer', () => {
17     beforeAll(() => {
18         localStorage.clear();
19     });
20
21     it('should return default state on initialisation', () => {
22         const initialState = undefined;
23         const state = authReducer(initialState, actions.INIT());
24         expect(state).toEqual({
25             apiToken: undefined,
26             user: undefined
27         });
28     });
29
30     it('should read user and api token from local storage on init if they are there', () => {
31         const initialState = undefined;
32
33         localStorage.setItem(API_TOKEN_KEY, "token");
34         localStorage.setItem(USER_EMAIL_KEY, "test@test.com");
35         localStorage.setItem(USER_FIRST_NAME_KEY, "John");
36         localStorage.setItem(USER_LAST_NAME_KEY, "Doe");
37
38         const state = authReducer(initialState, actions.INIT());
39         expect(state).toEqual({
40             apiToken: "token",
41             user: {
42                 email: "test@test.com",
43                 firstName: "John",
44                 lastName: "Doe"
45             }
46         });
47     });
48
49     it('should store token in local storage', () => {
50         const initialState = undefined;
51
52         const state = authReducer(initialState, actions.SAVE_API_TOKEN("token"));
53         expect(state).toEqual({
54             apiToken: "token",
55             user: undefined
56         });
57
58         expect(localStorage.getItem(API_TOKEN_KEY)).toBe("token");
59     });
60
61     it('should set user details on success fetch', () => {
62         const initialState = undefined;
63
64         const userDetails = {
65             email: "test@test.com",
66             first_name: "John",
67             last_name: "Doe",
68             is_admin: true
69         };
70
71         const state = authReducer(initialState, actions.USER_DETAILS_SUCCESS(userDetails));
72         expect(state).toEqual({
73             apiToken: undefined,
74             user: {
75                 email: "test@test.com",
76                 firstName: "John",
77                 lastName: "Doe"
78             }
79         });
80
81         expect(localStorage.getItem(API_TOKEN_KEY)).toBe("token");
82     });
83 });