index.test.tsx 9.23 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Provider } from 'jotai';
import mockDate from 'mockdate';
import { BrowserRouter } from 'react-router-dom';
import axios from 'axios';
import userEvent from '@testing-library/user-event';

import {
  render,
  RenderResult,
  screen,
  waitFor,
  SnackbarProvider,
} from '@centreon/ui';

import { areUserParametersLoadedAtom } from '../Main/useUser';
import { labelAlias } from '../Resources/translatedLabels';
import { platformInstallationStatusAtom } from '../platformInstallationStatusAtom';
import { userEndpoint } from '../api/endpoint';
19
import { labelCentreonWallpaper } from '../components/Wallpaper/translatedLabels';
20
21
22
23
24
25
26
27
28

import {
  labelCentreonLogo,
  labelDisplayThePassword,
  labelConnect,
  labelLoginSucceeded,
  labelPassword,
  labelRequired,
  labelHideThePassword,
29
  labelLoginWith,
30
  labelPasswordHasExpired,
31
} from './translatedLabels';
32
33
34
35
36
import {
  loginEndpoint,
  platformVersionsEndpoint,
  providersConfigurationEndpoint,
} from './api/endpoint';
37
38
39
40
41
42
43

import LoginPage from '.';

const mockedAxios = axios as jest.Mocked<typeof axios>;

const cancelTokenRequestParam = { cancelToken: {} };

44
jest.mock('../assets/logo-centreon-colors.png');
45
46
47
jest.mock('../assets/centreon-wallpaper-xl.jpg');
jest.mock('../assets/centreon-wallpaper-lg.jpg');
jest.mock('../assets/centreon-wallpaper-sm.jpg');
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

jest.mock('@centreon/ui-context', () =>
  jest.requireActual('centreon-frontend/packages/ui-context'),
);

const mockNow = '2020-01-01';

const retrievedUser = {
  alias: 'Admin alias',
  default_page: '/monitoring/resources',
  is_export_button_enabled: true,
  locale: 'fr_FR.UTF8',
  name: 'Admin',
  timezone: 'Europe/Paris',
  use_deprecated_pages: false,
};

const retrievedWeb = {
  web: {
    version: '21.10.1',
  },
};

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const retrievedProvidersConfiguration = [
  {
    authentication_uri:
      '/centreon/authentication/providers/configurations/local',
    id: 1,
    is_active: true,
    name: 'local',
  },
  {
    authentication_uri:
      '/centreon/authentication/providers/configurations/openid',
    id: 2,
    is_active: true,
    name: 'openid',
  },
  {
    authentication_uri:
      '/centreon/authentication/providers/configurations/ldap',
    id: 3,
    is_active: false,
    name: 'ldap',
  },
];

95
96
97
98
99
100
const retrievedTranslations = {
  en: {
    hello: 'Hello',
  },
};

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
const TestComponent = (): JSX.Element => (
  <BrowserRouter>
    <SnackbarProvider>
      <Provider
        initialValues={[
          [areUserParametersLoadedAtom, false],
          [
            platformInstallationStatusAtom,
            { availableVersion: null, installedVersion: '21.10.1' },
          ],
        ]}
      >
        <LoginPage />
      </Provider>
    </SnackbarProvider>
  </BrowserRouter>
);

const renderLoginPage = (): RenderResult => render(<TestComponent />);

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
const mockPostLoginSuccess = (): void => {
  mockedAxios.post.mockResolvedValue({
    data: {
      redirect_uri: '/monitoring/resources',
    },
  });
};

const mockPostLoginInvalidCredentials = (): void => {
  mockedAxios.post.mockRejectedValueOnce({
    response: {
      data: { code: 401, message: labelInvalidCredentials },
      status: 401,
    },
  });
};

const mockPostLoginPasswordExpired = (): void => {
  mockedAxios.post.mockRejectedValue({
    response: {
      data: {
        password_is_expired: true,
        redirect_uri: '/monitoring/resources',
      },
      status: 401,
    },
  });
};

150
151
152
153
154
155
156
157
158
159
160
161
162
const labelError = 'This is an error from the server';

const mockPostLoginServerError = (): void => {
  mockedAxios.post.mockRejectedValue({
    response: {
      data: {
        message: labelError,
      },
      status: 500,
    },
  });
};

163
const labelInvalidCredentials = 'Invalid credentials';
164

165
166
167
168
describe('Login Page', () => {
  beforeEach(() => {
    mockDate.set(mockNow);
    mockedAxios.get
169
170
171
      .mockResolvedValueOnce({
        data: retrievedTranslations,
      })
172
173
174
      .mockResolvedValueOnce({
        data: retrievedWeb,
      })
175
176
177
      .mockResolvedValueOnce({
        data: retrievedProvidersConfiguration,
      })
178
179
180
      .mockResolvedValue({
        data: retrievedUser,
      });
181
    window.history.pushState({}, '', '/');
182
183
184
185
186
187
188
189
190
  });

  afterEach(() => {
    mockDate.reset();
    mockedAxios.get.mockReset();
    mockedAxios.post.mockReset();
  });

  it('displays the login form', async () => {
191
    mockPostLoginSuccess();
192
193
194
195
196
197
198
199
200
    renderLoginPage();

    await waitFor(() => {
      expect(mockedAxios.get).toHaveBeenCalledWith(
        platformVersionsEndpoint,
        cancelTokenRequestParam,
      );
    });

201
202
203
204
205
    expect(mockedAxios.get).toHaveBeenCalledWith(
      providersConfigurationEndpoint,
      cancelTokenRequestParam,
    );

206
207
    expect(screen.getByLabelText(labelCentreonWallpaper)).toBeInTheDocument();
    expect(screen.getByLabelText(labelCentreonLogo)).toBeInTheDocument();
208
209
210
    expect(screen.getByLabelText(labelAlias)).toBeInTheDocument();
    expect(screen.getByLabelText(labelPassword)).toBeInTheDocument();
    expect(screen.getByLabelText(labelConnect)).toBeInTheDocument();
211
212
213
    await waitFor(() => {
      expect(screen.getByText('v. 21.10.1')).toBeInTheDocument();
    });
214
215
216
217
218
219
220
    expect(screen.getByText(`${labelLoginWith} openid`)).toHaveAttribute(
      'href',
      '/centreon/authentication/providers/configurations/openid',
    );
    expect(
      screen.queryByText(`${labelLoginWith} ldap`),
    ).not.toBeInTheDocument();
221
222
223
224
    expect(screen.getByText('Copyright © 2005 - 2020')).toBeInTheDocument();
  });

  it(`submits the credentials when they are valid and the "${labelConnect}" is clicked`, async () => {
225
    mockPostLoginSuccess();
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
    renderLoginPage();

    userEvent.type(screen.getByLabelText(labelAlias), 'admin');
    userEvent.type(screen.getByLabelText(labelPassword), 'centreon');
    userEvent.click(screen.getByLabelText(labelConnect));

    await waitFor(() => {
      expect(mockedAxios.post).toHaveBeenCalledWith(loginEndpoint, {
        login: 'admin',
        password: 'centreon',
      });
    });
    expect(mockedAxios.get).toHaveBeenCalledWith(
      userEndpoint,
      cancelTokenRequestParam,
    );

    await waitFor(() => {
      expect(screen.getByText(labelLoginSucceeded)).toBeInTheDocument();
    });

    expect(window.location.href).toBe('http://localhost/monitoring/resources');
  });

  it(`does not submit the credentials when they are invalid and the "${labelConnect}" button is clicked`, async () => {
251
    mockPostLoginInvalidCredentials();
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
    renderLoginPage();

    userEvent.type(screen.getByLabelText(labelAlias), 'invalid_alias');
    userEvent.type(screen.getByLabelText(labelPassword), 'invalid_pwd');
    userEvent.click(screen.getByLabelText(labelConnect));

    await waitFor(() => {
      expect(mockedAxios.post).toHaveBeenCalledWith(loginEndpoint, {
        login: 'invalid_alias',
        password: 'invalid_pwd',
      });
    });
    expect(mockedAxios.get).not.toHaveBeenCalledWith(
      userEndpoint,
      cancelTokenRequestParam,
    );

    await waitFor(() => {
      expect(screen.getByText(labelInvalidCredentials)).toBeInTheDocument();
    });

    expect(window.location.href).toBe('http://localhost/');
  });

  it('displays errors when fields are cleared', async () => {
    renderLoginPage();

    expect(screen.getByLabelText(labelConnect)).toBeDisabled();

    userEvent.type(screen.getByLabelText(labelAlias), 'admin');
    userEvent.type(screen.getByLabelText(labelPassword), 'centreon');

    await waitFor(() => {
      expect(screen.getByLabelText(labelConnect)).not.toBeDisabled();
    });

    userEvent.type(screen.getByLabelText(labelAlias), '{selectall}{backspace}');
    userEvent.type(
      screen.getByLabelText(labelPassword),
      '{selectall}{backspace}',
    );

    await waitFor(() => {
      expect(screen.getByLabelText(labelConnect)).toBeDisabled();
    });

298
299
300
    await waitFor(() => {
      expect(screen.getAllByText(labelRequired)).toHaveLength(2);
    });
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
  });

  it('displays the password when the corresponding action is clicked', () => {
    renderLoginPage();

    userEvent.click(
      screen.getByLabelText(labelDisplayThePassword).firstChild as HTMLElement,
    );

    expect(screen.getByLabelText(labelPassword)).toHaveAttribute(
      'type',
      'text',
    );
    expect(screen.getByLabelText(labelHideThePassword)).toBeInTheDocument();
  });
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331

  it('redirects to the reset page when the submitted password is expired', async () => {
    mockPostLoginPasswordExpired();
    renderLoginPage();

    userEvent.type(screen.getByLabelText(labelAlias), 'admin');
    userEvent.type(screen.getByLabelText(labelPassword), 'centreon');

    userEvent.click(screen.getByLabelText(labelConnect));

    await waitFor(() => {
      expect(screen.getByText(labelPasswordHasExpired)).toBeInTheDocument();
    });

    expect(window.location.href).toBe('http://localhost/reset-password');
  });
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348

  it('stays on the login page when the login request returns a 500 error', async () => {
    mockPostLoginServerError();
    renderLoginPage();

    userEvent.type(screen.getByLabelText(labelAlias), 'admin');
    userEvent.type(screen.getByLabelText(labelPassword), 'centreon');

    userEvent.click(screen.getByLabelText(labelConnect));

    await waitFor(() => {
      expect(screen.getByText(labelError)).toBeInTheDocument();
    });

    expect(window.location.href).not.toBe('http://localhost/reset-password');
    expect(screen.getByLabelText(labelAlias)).toBeInTheDocument();
  });
349
});