From ec5d1a9ce9b82453c6fa565edcf0fbb9722d6fa3 Mon Sep 17 00:00:00 2001 From: Walter Rafelsberger Date: Fri, 13 Sep 2019 05:39:38 -0700 Subject: [PATCH] [ML] Fixes getTab() to always return an array. (#45616) - Fixes getTabs() to always return an array. I was wondering why TypeScript didn't flag the tabs.map(...) part because tabs could possibly be undefined. It's because Record assumes that every key exists. More on that can be found in this blog post. - This PR fixes a) the type of TAB_MAP by wrapping it in Partial<...> so it correctly flags the tabs.map() part with tabs possibly being undefined and b) fixes getTabs()'s return value by always returning an array. --- .../components/navigation_menu/tabs.test.tsx | 23 +++++++++++++++++++ .../components/navigation_menu/tabs.tsx | 6 ++--- 2 files changed, 26 insertions(+), 3 deletions(-) create mode 100644 x-pack/legacy/plugins/ml/public/components/navigation_menu/tabs.test.tsx diff --git a/x-pack/legacy/plugins/ml/public/components/navigation_menu/tabs.test.tsx b/x-pack/legacy/plugins/ml/public/components/navigation_menu/tabs.test.tsx new file mode 100644 index 0000000000000..74360ce8c788c --- /dev/null +++ b/x-pack/legacy/plugins/ml/public/components/navigation_menu/tabs.test.tsx @@ -0,0 +1,23 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getTabs } from './tabs'; + +describe('Navigation Menu: Tabs', () => { + test('getTabs() always returns an array', () => { + const tabs1 = getTabs('anomaly_detection', false); + expect(Array.isArray(tabs1)).toBeTruthy(); + expect(tabs1).toHaveLength(4); + + const tabs2 = getTabs('access-denied', false); + expect(Array.isArray(tabs2)).toBeTruthy(); + expect(tabs2).toHaveLength(0); + + const tabs3 = getTabs('datavisualizer', false); + expect(Array.isArray(tabs3)).toBeTruthy(); + expect(tabs3).toHaveLength(0); + }); +}); diff --git a/x-pack/legacy/plugins/ml/public/components/navigation_menu/tabs.tsx b/x-pack/legacy/plugins/ml/public/components/navigation_menu/tabs.tsx index 787f44f7cef90..5a1c120aa1c4e 100644 --- a/x-pack/legacy/plugins/ml/public/components/navigation_menu/tabs.tsx +++ b/x-pack/legacy/plugins/ml/public/components/navigation_menu/tabs.tsx @@ -17,8 +17,8 @@ interface Props { tabId: TabId; } -function getTabs(tabId: TabId, disableLinks: boolean): Tab[] { - const TAB_MAP: Record = { +export function getTabs(tabId: TabId, disableLinks: boolean): Tab[] { + const TAB_MAP: Partial> = { // overview: [], datavisualizer: [], data_frames: [], @@ -55,7 +55,7 @@ function getTabs(tabId: TabId, disableLinks: boolean): Tab[] { ], }; - return TAB_MAP[tabId]; + return TAB_MAP[tabId] || []; } enum TAB_TEST_SUBJECT {