@centreon/ui 23.10.34-MON-19940-Add-testIds-cloud-notifications.2 → 23.10.34-MON-19940-Add-testIds-cloud-notifications.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@centreon/ui",
3
- "version": "23.10.34-MON-19940-Add-testIds-cloud-notifications.2",
3
+ "version": "23.10.34-MON-19940-Add-testIds-cloud-notifications.3",
4
4
  "description": "Centreon UI Components",
5
5
  "scripts": {
6
6
  "eslint": "eslint ./src --ext .js,.jsx,.ts,.tsx --max-warnings 0",
@@ -0,0 +1,303 @@
1
+ /* eslint-disable */
2
+ /* tslint:disable */
3
+
4
+ /**
5
+ * Mock Service Worker (1.2.1).
6
+ * @see https://github.com/mswjs/msw
7
+ * - Please do NOT modify this file.
8
+ * - Please do NOT serve this file on production.
9
+ */
10
+
11
+ const INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'
12
+ const activeClientIds = new Set()
13
+
14
+ self.addEventListener('install', function () {
15
+ self.skipWaiting()
16
+ })
17
+
18
+ self.addEventListener('activate', function (event) {
19
+ event.waitUntil(self.clients.claim())
20
+ })
21
+
22
+ self.addEventListener('message', async function (event) {
23
+ const clientId = event.source.id
24
+
25
+ if (!clientId || !self.clients) {
26
+ return
27
+ }
28
+
29
+ const client = await self.clients.get(clientId)
30
+
31
+ if (!client) {
32
+ return
33
+ }
34
+
35
+ const allClients = await self.clients.matchAll({
36
+ type: 'window',
37
+ })
38
+
39
+ switch (event.data) {
40
+ case 'KEEPALIVE_REQUEST': {
41
+ sendToClient(client, {
42
+ type: 'KEEPALIVE_RESPONSE',
43
+ })
44
+ break
45
+ }
46
+
47
+ case 'INTEGRITY_CHECK_REQUEST': {
48
+ sendToClient(client, {
49
+ type: 'INTEGRITY_CHECK_RESPONSE',
50
+ payload: INTEGRITY_CHECKSUM,
51
+ })
52
+ break
53
+ }
54
+
55
+ case 'MOCK_ACTIVATE': {
56
+ activeClientIds.add(clientId)
57
+
58
+ sendToClient(client, {
59
+ type: 'MOCKING_ENABLED',
60
+ payload: true,
61
+ })
62
+ break
63
+ }
64
+
65
+ case 'MOCK_DEACTIVATE': {
66
+ activeClientIds.delete(clientId)
67
+ break
68
+ }
69
+
70
+ case 'CLIENT_CLOSED': {
71
+ activeClientIds.delete(clientId)
72
+
73
+ const remainingClients = allClients.filter((client) => {
74
+ return client.id !== clientId
75
+ })
76
+
77
+ // Unregister itself when there are no more clients
78
+ if (remainingClients.length === 0) {
79
+ self.registration.unregister()
80
+ }
81
+
82
+ break
83
+ }
84
+ }
85
+ })
86
+
87
+ self.addEventListener('fetch', function (event) {
88
+ const { request } = event
89
+ const accept = request.headers.get('accept') || ''
90
+
91
+ // Bypass server-sent events.
92
+ if (accept.includes('text/event-stream')) {
93
+ return
94
+ }
95
+
96
+ // Bypass navigation requests.
97
+ if (request.mode === 'navigate') {
98
+ return
99
+ }
100
+
101
+ // Opening the DevTools triggers the "only-if-cached" request
102
+ // that cannot be handled by the worker. Bypass such requests.
103
+ if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
104
+ return
105
+ }
106
+
107
+ // Bypass all requests when there are no active clients.
108
+ // Prevents the self-unregistered worked from handling requests
109
+ // after it's been deleted (still remains active until the next reload).
110
+ if (activeClientIds.size === 0) {
111
+ return
112
+ }
113
+
114
+ // Generate unique request ID.
115
+ const requestId = Math.random().toString(16).slice(2)
116
+
117
+ event.respondWith(
118
+ handleRequest(event, requestId).catch((error) => {
119
+ if (error.name === 'NetworkError') {
120
+ console.warn(
121
+ '[MSW] Successfully emulated a network error for the "%s %s" request.',
122
+ request.method,
123
+ request.url,
124
+ )
125
+ return
126
+ }
127
+
128
+ // At this point, any exception indicates an issue with the original request/response.
129
+ console.error(
130
+ `\
131
+ [MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
132
+ request.method,
133
+ request.url,
134
+ `${error.name}: ${error.message}`,
135
+ )
136
+ }),
137
+ )
138
+ })
139
+
140
+ async function handleRequest(event, requestId) {
141
+ const client = await resolveMainClient(event)
142
+ const response = await getResponse(event, client, requestId)
143
+
144
+ // Send back the response clone for the "response:*" life-cycle events.
145
+ // Ensure MSW is active and ready to handle the message, otherwise
146
+ // this message will pend indefinitely.
147
+ if (client && activeClientIds.has(client.id)) {
148
+ ;(async function () {
149
+ const clonedResponse = response.clone()
150
+ sendToClient(client, {
151
+ type: 'RESPONSE',
152
+ payload: {
153
+ requestId,
154
+ type: clonedResponse.type,
155
+ ok: clonedResponse.ok,
156
+ status: clonedResponse.status,
157
+ statusText: clonedResponse.statusText,
158
+ body:
159
+ clonedResponse.body === null ? null : await clonedResponse.text(),
160
+ headers: Object.fromEntries(clonedResponse.headers.entries()),
161
+ redirected: clonedResponse.redirected,
162
+ },
163
+ })
164
+ })()
165
+ }
166
+
167
+ return response
168
+ }
169
+
170
+ // Resolve the main client for the given event.
171
+ // Client that issues a request doesn't necessarily equal the client
172
+ // that registered the worker. It's with the latter the worker should
173
+ // communicate with during the response resolving phase.
174
+ async function resolveMainClient(event) {
175
+ const client = await self.clients.get(event.clientId)
176
+
177
+ if (client?.frameType === 'top-level') {
178
+ return client
179
+ }
180
+
181
+ const allClients = await self.clients.matchAll({
182
+ type: 'window',
183
+ })
184
+
185
+ return allClients
186
+ .filter((client) => {
187
+ // Get only those clients that are currently visible.
188
+ return client.visibilityState === 'visible'
189
+ })
190
+ .find((client) => {
191
+ // Find the client ID that's recorded in the
192
+ // set of clients that have registered the worker.
193
+ return activeClientIds.has(client.id)
194
+ })
195
+ }
196
+
197
+ async function getResponse(event, client, requestId) {
198
+ const { request } = event
199
+ const clonedRequest = request.clone()
200
+
201
+ function passthrough() {
202
+ // Clone the request because it might've been already used
203
+ // (i.e. its body has been read and sent to the client).
204
+ const headers = Object.fromEntries(clonedRequest.headers.entries())
205
+
206
+ // Remove MSW-specific request headers so the bypassed requests
207
+ // comply with the server's CORS preflight check.
208
+ // Operate with the headers as an object because request "Headers"
209
+ // are immutable.
210
+ delete headers['x-msw-bypass']
211
+
212
+ return fetch(clonedRequest, { headers })
213
+ }
214
+
215
+ // Bypass mocking when the client is not active.
216
+ if (!client) {
217
+ return passthrough()
218
+ }
219
+
220
+ // Bypass initial page load requests (i.e. static assets).
221
+ // The absence of the immediate/parent client in the map of the active clients
222
+ // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
223
+ // and is not ready to handle requests.
224
+ if (!activeClientIds.has(client.id)) {
225
+ return passthrough()
226
+ }
227
+
228
+ // Bypass requests with the explicit bypass header.
229
+ // Such requests can be issued by "ctx.fetch()".
230
+ if (request.headers.get('x-msw-bypass') === 'true') {
231
+ return passthrough()
232
+ }
233
+
234
+ // Notify the client that a request has been intercepted.
235
+ const clientMessage = await sendToClient(client, {
236
+ type: 'REQUEST',
237
+ payload: {
238
+ id: requestId,
239
+ url: request.url,
240
+ method: request.method,
241
+ headers: Object.fromEntries(request.headers.entries()),
242
+ cache: request.cache,
243
+ mode: request.mode,
244
+ credentials: request.credentials,
245
+ destination: request.destination,
246
+ integrity: request.integrity,
247
+ redirect: request.redirect,
248
+ referrer: request.referrer,
249
+ referrerPolicy: request.referrerPolicy,
250
+ body: await request.text(),
251
+ bodyUsed: request.bodyUsed,
252
+ keepalive: request.keepalive,
253
+ },
254
+ })
255
+
256
+ switch (clientMessage.type) {
257
+ case 'MOCK_RESPONSE': {
258
+ return respondWithMock(clientMessage.data)
259
+ }
260
+
261
+ case 'MOCK_NOT_FOUND': {
262
+ return passthrough()
263
+ }
264
+
265
+ case 'NETWORK_ERROR': {
266
+ const { name, message } = clientMessage.data
267
+ const networkError = new Error(message)
268
+ networkError.name = name
269
+
270
+ // Rejecting a "respondWith" promise emulates a network error.
271
+ throw networkError
272
+ }
273
+ }
274
+
275
+ return passthrough()
276
+ }
277
+
278
+ function sendToClient(client, message) {
279
+ return new Promise((resolve, reject) => {
280
+ const channel = new MessageChannel()
281
+
282
+ channel.port1.onmessage = (event) => {
283
+ if (event.data && event.data.error) {
284
+ return reject(event.data.error)
285
+ }
286
+
287
+ resolve(event.data)
288
+ }
289
+
290
+ client.postMessage(message, [channel.port2])
291
+ })
292
+ }
293
+
294
+ function sleep(timeMs) {
295
+ return new Promise((resolve) => {
296
+ setTimeout(resolve, timeMs)
297
+ })
298
+ }
299
+
300
+ async function respondWithMock(response) {
301
+ await sleep(response.delay)
302
+ return new Response(response.body, response)
303
+ }
@@ -13,6 +13,8 @@ import {
13
13
  CircularProgress
14
14
  } from '@mui/material';
15
15
 
16
+ import { DataTestAttributes } from '../@types/data-attributes';
17
+
16
18
  interface StylesProps {
17
19
  contentWidth?: number;
18
20
  }
@@ -29,18 +31,12 @@ const useStyles = makeStyles<StylesProps>()((theme, { contentWidth }) => ({
29
31
  }
30
32
  }));
31
33
 
32
- interface DialogDataTestId {
33
- dataTestIdCanceledButton?: string;
34
- dataTestIdConfirmButton?: string;
35
- }
36
-
37
34
  export type Props = {
38
35
  cancelDisabled?: boolean;
39
36
  children?: ReactNode;
40
37
  className?: string;
41
38
  confirmDisabled?: boolean;
42
39
  contentWidth?: number;
43
- dataTestId?: DialogDataTestId;
44
40
  dialogActionsClassName?: string;
45
41
  dialogConfirmButtonClassName?: string;
46
42
  dialogContentClassName?: string;
@@ -54,7 +50,8 @@ export type Props = {
54
50
  onConfirm: (event, value?) => void;
55
51
  open: boolean;
56
52
  submitting?: boolean;
57
- } & DialogProps;
53
+ } & DialogProps &
54
+ DataTestAttributes;
58
55
 
59
56
  const Dialog = ({
60
57
  open,
@@ -69,7 +66,6 @@ const Dialog = ({
69
66
  confirmDisabled = false,
70
67
  cancelDisabled = false,
71
68
  submitting = false,
72
- dataTestId,
73
69
  dialogPaperClassName,
74
70
  dialogTitleClassName,
75
71
  dialogContentClassName,
@@ -80,12 +76,6 @@ const Dialog = ({
80
76
  const { classes, cx } = useStyles({ contentWidth });
81
77
  const { t } = useTranslation();
82
78
 
83
- const dataTestIdConfirmButton =
84
- dataTestId?.dataTestIdConfirmButton ?? t(labelConfirm as string);
85
-
86
- const dataTestIdCanceledButton =
87
- dataTestId?.dataTestIdCanceledButton ?? t(labelCancel as string);
88
-
89
79
  return (
90
80
  <MuiDialog
91
81
  PaperProps={{
@@ -110,7 +100,7 @@ const Dialog = ({
110
100
  {onCancel && (
111
101
  <Button
112
102
  color="primary"
113
- data-testid={dataTestIdCanceledButton}
103
+ data-testid={t(labelCancel as string)}
114
104
  disabled={cancelDisabled}
115
105
  onClick={onCancel}
116
106
  >
@@ -121,7 +111,7 @@ const Dialog = ({
121
111
  aria-label={labelConfirm || ''}
122
112
  className={dialogConfirmButtonClassName}
123
113
  color="primary"
124
- data-testid={dataTestIdConfirmButton}
114
+ data-testid={t(labelConfirm as string)}
125
115
  disabled={confirmDisabled}
126
116
  endIcon={submitting && <CircularProgress size={15} />}
127
117
  onClick={onConfirm}
@@ -0,0 +1,161 @@
1
+ import {
2
+ Method,
3
+ MultiConnectedAutocompleteField,
4
+ TestQueryProvider
5
+ } from '@centreon/ui';
6
+
7
+ import { baseEndpoint, getEndpoint, label, placeholder } from './utils';
8
+
9
+ const optionOne = 'My Option 1';
10
+
11
+ describe('Multi connected autocomplete', () => {
12
+ beforeEach(() => {
13
+ cy.fixture('inputField/listOptions').then((optionsData) => {
14
+ cy.interceptAPIRequest({
15
+ alias: 'getListOptions',
16
+ method: Method.GET,
17
+ path: `${baseEndpoint}**`,
18
+ response: optionsData
19
+ });
20
+ });
21
+
22
+ cy.fixture('inputField/searchedOption').then((optionData) => {
23
+ cy.interceptAPIRequest({
24
+ alias: 'getSearchedOption',
25
+ method: Method.GET,
26
+ path: `${baseEndpoint}**`,
27
+ query: {
28
+ name: 'search',
29
+ value: JSON.stringify({
30
+ $and: [{ 'host.name': { $lk: `%${optionOne}%` } }]
31
+ })
32
+ },
33
+ response: optionData
34
+ });
35
+ });
36
+
37
+ cy.mount({
38
+ Component: (
39
+ <TestQueryProvider>
40
+ <div style={{ paddingTop: 20 }}>
41
+ <MultiConnectedAutocompleteField
42
+ field="host.name"
43
+ getEndpoint={getEndpoint}
44
+ label={label}
45
+ placeholder={placeholder}
46
+ />
47
+ </div>
48
+ </TestQueryProvider>
49
+ )
50
+ });
51
+ });
52
+
53
+ it('displays and hides the list when the user double-clicks on the input', () => {
54
+ cy.contains(label).should('be.visible');
55
+
56
+ cy.get('[data-testid="Multi Connected Autocomplete"]').as('input');
57
+
58
+ cy.get('@input').click();
59
+
60
+ cy.waitForRequest('@getListOptions');
61
+
62
+ cy.get('@input').invoke('attr', 'placeholder').should('equal', placeholder);
63
+
64
+ cy.findByRole('presentation').as('listOptions');
65
+
66
+ cy.get('@listOptions').should('be.visible');
67
+
68
+ cy.fixture('inputField/listOptions').then((optionsData) => {
69
+ cy.get('@listOptions').within(() => {
70
+ optionsData.result.forEach((option) => {
71
+ cy.contains(option.name);
72
+ });
73
+ });
74
+ });
75
+
76
+ cy.matchImageSnapshot(
77
+ 'displays the list when the user clicks on the input'
78
+ );
79
+
80
+ cy.get('@input').click();
81
+
82
+ cy.get('@listOptions').should('not.exist');
83
+
84
+ cy.matchImageSnapshot('hides the list when the user clicks on the input');
85
+ });
86
+
87
+ it('displays exactly one option on the list when the user types that option', () => {
88
+ cy.get('[data-testid="Multi Connected Autocomplete"]').as('input');
89
+
90
+ cy.get('@input').click();
91
+
92
+ cy.waitForRequest('@getListOptions');
93
+
94
+ cy.findByRole('presentation').as('listOptions');
95
+
96
+ cy.get('@listOptions').should('be.visible');
97
+
98
+ cy.get('@input').type(optionOne);
99
+
100
+ cy.waitForRequest('@getSearchedOption');
101
+
102
+ cy.fixture('inputField/searchedOption').then((optionData) => {
103
+ cy.get('@listOptions')
104
+ .find('li')
105
+ .should('have.length', optionData.result.length);
106
+ });
107
+
108
+ cy.get('@listOptions').within(() => {
109
+ cy.contains(optionOne).should('be.visible');
110
+ });
111
+
112
+ cy.matchImageSnapshot();
113
+ });
114
+
115
+ it('displays all options on the list when the user searches for and selects an option', () => {
116
+ cy.get('[data-testid="Multi Connected Autocomplete"]').as('input');
117
+
118
+ cy.get('@input').click();
119
+
120
+ cy.waitForRequest('@getListOptions');
121
+
122
+ cy.findByRole('presentation').as('listOptions');
123
+
124
+ cy.get('@listOptions').should('be.visible');
125
+
126
+ cy.get('@input').type(optionOne);
127
+
128
+ cy.waitForRequest('@getSearchedOption');
129
+
130
+ cy.fixture('inputField/searchedOption').then((optionData) => {
131
+ cy.get('@listOptions')
132
+ .find('li')
133
+ .should('have.length', optionData.result.length);
134
+ });
135
+
136
+ cy.get('[type="checkbox"]').check();
137
+ cy.get('@input')
138
+ .parent()
139
+ .within(() => {
140
+ cy.contains(optionOne).should('be.visible');
141
+
142
+ cy.get('[data-testid="CancelIcon"]').should('be.visible');
143
+ });
144
+
145
+ cy.waitForRequest('@getListOptions');
146
+
147
+ cy.fixture('inputField/listOptions').then((optionsData) => {
148
+ cy.get('@listOptions')
149
+ .find('li')
150
+ .should('have.length', optionsData.result.length);
151
+
152
+ cy.get('@listOptions').within(() => {
153
+ optionsData.result.forEach((option) => {
154
+ cy.contains(option.name);
155
+ });
156
+ });
157
+ });
158
+
159
+ cy.matchImageSnapshot();
160
+ });
161
+ });
@@ -7,30 +7,11 @@ import {
7
7
  resetMocks,
8
8
  waitFor
9
9
  } from '../../../../../../test/testRenderer';
10
- import { buildListingEndpoint } from '../../../../..';
11
10
  import TestQueryProvider from '../../../../../api/TestQueryProvider';
12
11
 
13
- import MultiConnectedAutocompleteField from '.';
14
-
15
- const baseEndpoint = 'endpoint';
16
-
17
- const getEndpoint = (parameters): string => {
18
- return buildListingEndpoint({ baseEndpoint, parameters });
19
- };
12
+ import { baseEndpoint, getEndpoint, label, optionsData } from './utils';
20
13
 
21
- const label = 'Multi Connected Autocomplete';
22
-
23
- const optionsData = {
24
- meta: {
25
- limit: 2,
26
- page: 1,
27
- total: 20
28
- },
29
- result: [
30
- { id: 0, name: 'My Option 1' },
31
- { id: 1, name: 'My Option 2' }
32
- ]
33
- };
14
+ import MultiConnectedAutocompleteField from '.';
34
15
 
35
16
  const renderMultiAutocompleteField = (): RenderResult =>
36
17
  render(
@@ -0,0 +1,22 @@
1
+ import { buildListingEndpoint } from '../../../../../..';
2
+
3
+ export const baseEndpoint = './endpoint';
4
+
5
+ export const getEndpoint = (parameters): string => {
6
+ return buildListingEndpoint({ baseEndpoint, parameters });
7
+ };
8
+
9
+ export const label = 'Multi Connected Autocomplete';
10
+ export const placeholder = 'Type here...';
11
+
12
+ export const optionsData = {
13
+ meta: {
14
+ limit: 2,
15
+ page: 1,
16
+ total: 20
17
+ },
18
+ result: [
19
+ { id: 0, name: 'My Option 1' },
20
+ { id: 1, name: 'My Option 2' }
21
+ ]
22
+ };
@@ -65,6 +65,9 @@ const ConnectedAutocompleteField = (
65
65
  const [searchParameter, setSearchParameter] = useState<
66
66
  SearchParameter | undefined
67
67
  >(undefined);
68
+
69
+ const [autocompleteChangedValue, setAutocompleteChangedValue] =
70
+ useState<Array<SelectEntry>>();
68
71
  const debounce = useDebounce({
69
72
  functionToDebounce: (value): void => {
70
73
  setSearchParameter(getSearchParameter(value));
@@ -274,6 +277,13 @@ const ConnectedAutocompleteField = (
274
277
  );
275
278
  }, useDeepCompare([searchConditions]));
276
279
 
280
+ useEffect(() => {
281
+ if (!autocompleteChangedValue && !props?.value) {
282
+ return;
283
+ }
284
+ setSearchParameter(undefined);
285
+ }, [autocompleteChangedValue, props?.value]);
286
+
277
287
  useEffect(() => {
278
288
  if (!optionsOpen) {
279
289
  return;
@@ -289,6 +299,7 @@ const ConnectedAutocompleteField = (
289
299
  open={optionsOpen}
290
300
  options={options}
291
301
  renderOption={renderOptions}
302
+ onChange={(_, value) => setAutocompleteChangedValue(value)}
292
303
  onClose={(): void => setOptionsOpen(false)}
293
304
  onOpen={(): void => setOptionsOpen(true)}
294
305
  onTextChange={changeText}
@@ -11,7 +11,7 @@ import { userAtom } from '@centreon/ui-context';
11
11
 
12
12
  import { retrievedUser } from './mockedData';
13
13
 
14
- import TimePeriod from '.';
14
+ import TimePeriod from './index';
15
15
 
16
16
  dayjs.extend(timezonePlugin);
17
17
  dayjs.extend(utcPlugin);