summaryrefslogtreecommitdiffstats
path: root/ui-react/src/components/dialogs/ManageDictionaries/ManageDictionaries.test.js
blob: a4c1335d873ff9459ad3a5d7133b509e52ec331d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
251
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*-
 * ============LICENSE_START=======================================================
 * ONAP CLAMP
 * ================================================================================
 * Copyright (C) 2019 AT&T Intellectual Property. All rights
 *                             reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END============================================
 * ===================================================================
 *
 */
import React from 'react';
import { shallow } from 'enzyme';
import { mount } from 'enzyme';
import { render } from 'enzyme';
import ManageDictionaries from './ManageDictionaries';
import TemplateMenuService from '../../../api/TemplateService'

const TestDictionaryElements = {
    name: "test",
    secondLevelDictionary: 0,
    subDictionaryType: "", 
    dictionaryElements: [
      {
        shortName: "alertType",
        name: "Alert Type",
        description: "Type of Alert",
        type: "string",
        subDictionary: "", 
        createdDate: "2020-06-12T13:58:51.443931Z",
        updatedDate: "2020-06-13T16:27:57.084870Z",
        updatedBy: "admin",
        createdBy: "admin"
      }
    ]
};

const TestDictionaries =
[
  {
    name: "test",
    secondLevelDictionary: 0,
    subDictionaryType: "string",
    dictionaryElements: [ TestDictionaryElements ],
    createdDate: "2020-06-14T21:00:33.231166Z",
    updatedDate: "2020-06-14T21:00:33.231166Z",
    updatedBy: "admin",
    createdBy: "admin"
  },
  {
    name: "testSub1",
    secondLevelDictionary: 1,
    subDictionaryType: "string",
    dictionaryElements: [
      {
        shortName: "subElem",
        name: "Sub Element",
        description: "Sub Element Description",
        type: "string",
        createdDate: "2020-06-14T21:04:44.402287Z",
        updatedDate: "2020-06-14T21:04:44.402287Z",
        updatedBy: "admin",
        createdBy: "admin"
      }
    ],
    createdDate: "2020-06-14T21:01:16.390250Z",
    updatedDate: "2020-06-14T21:01:16.390250Z",
    updatedBy: "admin",
    createdBy: "admin"
  }
];


const historyMock = { push: jest.fn() };

let errorMessage = '';

window.alert = jest.fn().mockImplementation((mesg) => { errorMessage = mesg ; return });

TemplateMenuService.getDictionary = jest.fn().mockImplementation(() => {
	return Promise.resolve(TestDictionaries);
});

TemplateMenuService.insDictionary = jest.fn().mockImplementation(() => {
	return Promise.resolve({ ok: true, status: 200 });
});

TemplateMenuService.deleteDictionary = jest.fn().mockImplementation(() => {
	return Promise.resolve("200");
});

TemplateMenuService.getDictionaryElements = jest.fn().mockImplementation(() => {
	return Promise.resolve(TestDictionaryElements);
});

TemplateMenuService.deleteDictionaryElements = jest.fn().mockImplementation(() => {
	return Promise.resolve("200");
});

TemplateMenuService.insDictionaryElements = jest.fn().mockImplementation(() => {
	return Promise.resolve("200");
});


describe('Verify ManageDictionaries', () => {

	beforeEach(() => {
		fetch.resetMocks();
	});

	it('Test API Successful', () => {
		fetch.mockImplementationOnce(() => {
			return Promise.resolve({
				ok: true,
				status: 200,
				json: () => {
					return Promise.resolve({
						"name": "vtest",
						"secondLevelDictionary": 1,
						"subDictionaryType": "string",
						"updatedBy": "test",
						"updatedDate": "05-07-2019 19:09:42"
					});
				}
			});
		});
		const component = shallow(<ManageDictionaries />);
		expect(component).toMatchSnapshot();
	});

	it('Test API Exception', () => {
		fetch.mockImplementationOnce(() => {
			return Promise.resolve({
				ok: false,
				status: 500,
				json: () => {
					return Promise.resolve({
						"name": "vtest",
						"secondLevelDictionary": 1,
						"subDictionaryType": "string",
						"updatedBy": "test",
						"updatedDate": "05-07-2019 19:09:42"
					});
				}
			});
		});
		const component = shallow(<ManageDictionaries />);
	});

	it('Test Table icons', () => {

		const component = mount(<ManageDictionaries />);
		expect(component.find('[className="MuiSelect-icon MuiTablePagination-selectIcon"]')).toBeTruthy();
	});

	test('Test add/replace and delete dictionary requests', async () => {

		const component = shallow(<ManageDictionaries history={historyMock}/>)
		const instance = component.instance();

		const flushPromises = () => new Promise(setImmediate);

		instance.addReplaceDictionaryRequest({name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string"});
		instance.deleteDictionaryRequest("test");

		await flushPromises();

		expect(component.state('currentSelectedDictionary')).toEqual(null);
		expect(component.state('dictionaries')).toEqual(TestDictionaries);
	});

	test('Test update dictionary row', async () => {

		const component = shallow(<ManageDictionaries history={historyMock}/>)
		const instance = component.instance();
		const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" };

		await expect(instance.updateDictionaryRow(rowData, rowData)).resolves.toEqual(undefined);

	}, 2000);

	test('Test add dictionary row', async () => {

		const addReplaceRequest = jest.spyOn(ManageDictionaries.prototype,'addReplaceDictionaryRequest');
		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();
		const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" };

		await instance.addDictionaryRow(rowData);
                expect(addReplaceRequest).toHaveBeenCalledWith(rowData);

	}, 2000);

	test('Test add dictionary row with errors name already exists', async () => {

		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();
		let  rowData = { name: "test", secondLevelDictionary: 0, subDictionaryType: "" };

		await expect(instance.addDictionaryRow(rowData)).rejects.toEqual(undefined);

	}, 2000);

	test('Test add dictionary row with errors illegal chars in name', async () => {

		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();
		let  rowData = { name: "test@@", secondLevelDictionary: 0, subDictionaryType: "" };

		await expect(instance.addDictionaryRow(rowData)).rejects.toEqual(undefined);

	}, 2000);

	test('Test update dictionary row with errors illegal chars in name', async () => {

		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();
		let  rowData = { name: "test@@", secondLevelDictionary: 0, subDictionaryType: "" };

		await expect(instance.updateDictionaryRow(rowData)).rejects.toEqual(undefined);
	});


	test('Test add dictionary row with errors (illegal chars)', async () => {

		const addReplaceRequest = jest.spyOn(ManageDictionaries.prototype,'addReplaceDictionaryRequest');
		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();
		let  rowData = { name: "test@@", secondLevelDictionary: 0, subDictionaryType: "" };

		await expect(instance.addDictionaryRow(rowData)).rejects.toEqual(undefined);

	}, 2000);


	test('Test delete dictionary row', async () => {

		const deleteRequest = jest.spyOn(ManageDictionaries.prototype,'deleteDictionaryRequest');
		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();
		const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" };

		await instance.deleteDictionaryRow(rowData);
                expect(deleteRequest).toHaveBeenCalledWith("newdict");

	}, 2000);

	test('Test handle select dictionary row click', async () => {

		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();
		const rowData = { name: "newdict", secondLevelDictionary: 0, subDictionaryType: "string" };

		instance.handleDictionaryRowClick("event", rowData);
		expect(component.state('currentSelectedDictionary')).toEqual("newdict");
	}, 2000);

	test('Test dictionary element row add, update, delete', async () => {

		const rowData = {
			createdBy: "admin",
			createdDate: "2020-06-15T13:59:20.467381Z",
			description: "Description",
			name: "Some Elem",
			shortName: "someElem",
			type: "string",
			updatedBy: "admin",
			updatedDate: "2020-06-15T13:59:20.467381Z"
		};

		const component = shallow(<ManageDictionaries/>)
		const instance = component.instance();

		const badRowData = {
			description: "Description",
			name: "Some Elem",
			shortName: "someElem",
			type: "string"
		};

                await instance.clickHandler();
                await instance.getDictionaryElements("test");

		await expect(instance.addDictionaryElementRow(rowData)).resolves.toEqual(undefined);
		await expect(instance.updateDictionaryElementRow(rowData, rowData)).resolves.toEqual(undefined);
		await expect(instance.deleteDictionaryElementRow(rowData)).resolves.toEqual(undefined);
	});

	test('Test dictionary element row add with errors', async () => {

		const badRowData = {
			description: "",
			name: "",
			shortName: "some#Elem",
			type: ""
		};

		const component = shallow(<ManageDictionaries/>)
		const instance = component.instance();

		await expect(instance.addDictionaryElementRow(badRowData)).rejects.toEqual("");
	});

	test('Test dictionary element update with error illegal name', async () => {

		const badRowData = {
			description: "",
			name: "test@@",
			shortName: "some#Elem",
			type: ""
		};

		const component = shallow(<ManageDictionaries/>)
		const instance = component.instance();

		await expect(instance.updateDictionaryElementRow(badRowData)).rejects.toEqual(undefined);
	});

	test('Test dictionary element addition with duplicate name error', async () => {

		const badRowData = {
			description: "description",
			name: "Alert Type",
			shortName: "alertType",
			type: "string"
		};

		const component = shallow(<ManageDictionaries/>)
		const instance = component.instance();

		component.setState({ currentSelectedDictionary: 'test' });

		await instance.getDictionaryElements();
		await expect(instance.addDictionaryElementRow(badRowData)).rejects.toEqual("");
	});

	test('Test dictionary element addition with empty name error', async () => {

		const badRowData = {
			description: "description",
			name: "Alert Type",
			shortName: "",
			type: "string"
		};

		const component = shallow(<ManageDictionaries/>)
		const instance = component.instance();

		component.setState({ currentSelectedDictionary: 'test' });

		await instance.getDictionaryElements();
		await expect(instance.addDictionaryElementRow(badRowData)).rejects.toEqual("");
	});


	it('Test Import CSV Sunny Day', async () => {

                TemplateMenuService.insDictionaryElements = jest.fn().mockImplementation(() => {
                        return Promise.resolve({ ok: true, status: 200 });
                });

                let rawCsvData = '"Element Short Name","Element Name","Element Description","Element Type","Sub-Dictionary"\n';
                rawCsvData += '"alertType","Alert Type","Alert Type Description","string","","admin","2020-06-11T13:56:14.927437Z"';

                let expectedResult = [
                                {
                                        description: "Alert Type Description",
                                        name: "Alert Type",
                                        shortName: "alertType",
                                        subDictionary: "",
                                        type: "string"
                                }
		];

		const updateDictionaryElementsRequest = jest.spyOn(ManageDictionaries.prototype,'updateDictionaryElementsRequest');

		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();

		await expect(instance.importCsvData(rawCsvData)).toEqual('');
                expect(updateDictionaryElementsRequest).toHaveBeenCalledWith(expectedResult);
	});

	it('Test Import CSV Mandatory Field Check Errors', () => {

                let rawCsvData = '"Element Short Name","Element Name","Element Description","Element Type","Sub-Dictionary"\n';
                rawCsvData += '"","","","","","",""';

		// The empty values for all the fields in row 1 of the rawCsvData will trigger a bunch of errors.
		// Getting Enzyme to properly match them with embedded newlines turned out to be impossible
		// and maybe not desirable anyway; so our test for "success" here is simply that the
		// routine returns a non-empty error string.

		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();
		expect(instance.importCsvData(rawCsvData)).not.toEqual('');
	});

	it('Test Import CSV Errors in Row Data', async () => {

                TemplateMenuService.insDictionaryElements = jest.fn().mockImplementation(() => {
                        return Promise.resolve({ ok: true, status: 200 });
                });

                let rawCsvData = '"Element Short Name","Element Name","Element Description","Element Type","Sub-Dictionary"\n';
                rawCsvData += '"alert@Type","Alert Type","Alert Type Description","strin","subby","admin","2020-06-11T13:56:14.927437Z"';

                let expectedResult = [
                                {
                                        description: "Alert Type Description",
                                        name: "Alert Type",
                                        shortName: "alertType",
                                        subDictionary: "",
                                        type: "string"
                                }
		];

		const updateDictionaryElementsRequest = jest.spyOn(ManageDictionaries.prototype,'updateDictionaryElementsRequest');

		const component = shallow(<ManageDictionaries />)
		const instance = component.instance();

		await expect(instance.importCsvData(rawCsvData)).not.toEqual('');
	});


	it('Test handleClose', () => {
		fetch.mockImplementationOnce(() => {
			return Promise.resolve({
				ok: true,
				status: 200,
				json: () => {
					return Promise.resolve({
						"name": "vtest",
						"secondLevelDictionary": 1,
						"subDictionaryType": "string",
						"updatedBy": "test",
						"updatedDate": "05-07-2019 19:09:42"
					});
				}
			});
		});
		const handleClose = jest.spyOn(ManageDictionaries.prototype,'handleClose');
		const component = shallow(<ManageDictionaries history={historyMock} />)
		component.find('[variant="secondary"]').prop('onClick')();
		expect(handleClose).toHaveBeenCalledTimes(1);
		expect(component.state('show')).toEqual(false);
		expect(historyMock.push.mock.calls[0]).toEqual([ '/']);
		handleClose.mockClear();
	});
});