]> source.dussan.org Git - sonarqube.git/commitdiff
[NO JIRA] Small maintainability improvements
authorWouter Admiraal <wouter.admiraal@sonarsource.com>
Tue, 26 Dec 2023 10:48:30 +0000 (11:48 +0100)
committersonartech <sonartech@sonarsource.com>
Thu, 28 Dec 2023 20:03:00 +0000 (20:03 +0000)
server/sonar-web/src/main/js/apps/projectInformation/badges/ProjectBadges.tsx
server/sonar-web/src/main/js/apps/projectInformation/badges/__tests__/ProjectBadges-test.tsx

index b6882df187e9042bd4d7a7b15e21d9922a618280..0f735d2a6fd261054d72259d76889ffd4cf142e5 100644 (file)
@@ -55,18 +55,18 @@ export default function ProjectBadges(props: ProjectBadgesProps) {
     component: { key: project, qualifier, configuration },
   } = props;
   const [selectedType, setSelectedType] = useState(BadgeType.measure);
-  const [metricOptions, setMetricOptions] = useState(MetricKey.alert_status);
-  const [formatOption, setFormatOption] = useState<BadgeFormats>('md');
+  const [selectedMetric, setSelectedMetric] = useState(MetricKey.alert_status);
+  const [selectedFormat, setSelectedFormat] = useState<BadgeFormats>('md');
   const {
     data: token,
     isLoading: isLoadingToken,
     isFetching: isFetchingToken,
   } = useBadgeTokenQuery(project);
-  const { data: metricsOptions, isLoading: isLoadingMetrics } = useBadgeMetricsQuery();
+  const { data: metricOptions, isLoading: isLoadingMetrics } = useBadgeMetricsQuery();
   const { mutate: renewToken, isLoading: isRenewing } = useRenewBagdeTokenMutation();
   const isLoading = isLoadingMetrics || isLoadingToken || isRenewing;
 
-  const handleSelectBadge = (selectedType: BadgeType) => {
+  const handleSelectType = (selectedType: BadgeType) => {
     setSelectedType(selectedType);
   };
 
@@ -83,8 +83,8 @@ export default function ProjectBadges(props: ProjectBadgesProps) {
 
   const fullBadgeOptions: BadgeOptions = {
     project,
-    metric: metricOptions,
-    format: formatOption,
+    metric: selectedMetric,
+    format: selectedFormat,
     ...getBranchLikeQuery(branchLike),
   };
   const canRenew = configuration?.showSettings;
@@ -98,7 +98,7 @@ export default function ProjectBadges(props: ProjectBadgesProps) {
         <div className="sw-flex sw-space-x-4 sw-mb-4">
           <IllustratedSelectionCard
             className="sw-w-abs-300 it__badge-button"
-            onClick={() => handleSelectBadge(BadgeType.measure)}
+            onClick={() => handleSelectType(BadgeType.measure)}
             selected={BadgeType.measure === selectedType}
             image={
               <img
@@ -110,7 +110,7 @@ export default function ProjectBadges(props: ProjectBadgesProps) {
           />
           <IllustratedSelectionCard
             className="sw-w-abs-300 it__badge-button"
-            onClick={() => handleSelectBadge(BadgeType.qualityGate)}
+            onClick={() => handleSelectType(BadgeType.qualityGate)}
             selected={BadgeType.qualityGate === selectedType}
             image={
               <img
@@ -134,13 +134,13 @@ export default function ProjectBadges(props: ProjectBadgesProps) {
           <InputSelect
             className="sw-w-abs-300"
             inputId="badge-param-customize"
-            options={metricsOptions}
-            onChange={(value) => {
-              if (value) {
-                setMetricOptions(value.value);
+            options={metricOptions}
+            onChange={(option) => {
+              if (option) {
+                setSelectedMetric(option.value);
               }
             }}
-            value={metricsOptions.find((m) => m.value === metricOptions)}
+            value={metricOptions.find((m) => m.value === selectedMetric)}
           />
         </FormField>
       )}
@@ -154,10 +154,10 @@ export default function ProjectBadges(props: ProjectBadgesProps) {
             options={formatOptions}
             onChange={(value: BadgeFormats) => {
               if (value) {
-                setFormatOption(value);
+                setSelectedFormat(value);
               }
             }}
-            value={formatOption}
+            value={selectedFormat}
           />
         </div>
       </FormField>
index 95d3c44fb637490a36919cff213c2ed56228021b..51cac5fa82df6079f823ef69986067e5b15d2e26 100644 (file)
@@ -17,7 +17,7 @@
  * along with this program; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
  */
-import { screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, screen, waitFor } from '@testing-library/react';
 import userEvent from '@testing-library/user-event';
 import * as React from 'react';
 import selectEvent from 'react-select-event';
@@ -26,7 +26,6 @@ import { mockBranch } from '../../../../helpers/mocks/branch-like';
 import { mockComponent } from '../../../../helpers/mocks/component';
 import { renderComponent } from '../../../../helpers/testReactTestingUtils';
 import { Location } from '../../../../helpers/urls';
-import { ComponentQualifier } from '../../../../types/component';
 import { MetricKey } from '../../../../types/metrics';
 import ProjectBadges, { ProjectBadgesProps } from '../ProjectBadges';
 import { BadgeType } from '../utils';
@@ -43,38 +42,29 @@ jest.mock('../../../../api/project-badges', () => ({
 }));
 
 jest.mock('../../../../api/web-api', () => ({
-  fetchWebApi: () =>
-    Promise.resolve([
-      {
-        path: 'api/project_badges',
-        actions: [
-          {
-            key: 'measure',
-            // eslint-disable-next-line local-rules/use-metrickey-enum
-            params: [{ key: 'metric', possibleValues: ['alert_status', 'coverage'] }],
-          },
-        ],
-      },
-    ]),
+  fetchWebApi: jest.fn().mockResolvedValue([
+    {
+      path: 'api/project_badges',
+      actions: [
+        {
+          key: 'measure',
+          // eslint-disable-next-line local-rules/use-metrickey-enum
+          params: [{ key: 'metric', possibleValues: ['alert_status', 'coverage'] }],
+        },
+      ],
+    },
+  ]),
 }));
 
 it('should renew token', async () => {
   const user = userEvent.setup();
   jest.mocked(getProjectBadgesToken).mockResolvedValueOnce('foo').mockResolvedValueOnce('bar');
-  renderProjectBadges({
-    component: mockComponent({ configuration: { showSettings: true } }),
-  });
-
-  await waitFor(() =>
-    expect(screen.getByAltText(`overview.badges.${BadgeType.qualityGate}.alt`)).toHaveAttribute(
-      'src',
-      'host/api/project_badges/quality_gate?branch=branch-6.7&project=my-project&token=foo',
-    ),
-  );
+  renderProjectBadges();
+  await appLoaded();
 
   expect(screen.getByAltText(`overview.badges.${BadgeType.measure}.alt`)).toHaveAttribute(
     'src',
-    'host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=foo',
+    `host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=${MetricKey.alert_status}&token=foo`,
   );
 
   await user.click(screen.getByText('overview.badges.renew'));
@@ -88,32 +78,37 @@ it('should renew token', async () => {
 
   expect(screen.getByAltText(`overview.badges.${BadgeType.measure}.alt`)).toHaveAttribute(
     'src',
-    'host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=bar',
+    `host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=${MetricKey.alert_status}&token=bar`,
   );
 });
 
 it('should update params', async () => {
-  renderProjectBadges({
-    component: mockComponent({ configuration: { showSettings: true } }),
-  });
+  renderProjectBadges();
+  await appLoaded();
 
   expect(
-    await screen.findByText(
-      '[![alert_status](host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=foo)](/dashboard)',
+    screen.getByText(
+      `[![${MetricKey.alert_status}](host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=${MetricKey.alert_status}&token=foo)](/dashboard)`,
     ),
   ).toBeInTheDocument();
 
-  await selectEvent.select(screen.getByLabelText('overview.badges.format'), [
-    'overview.badges.options.formats.url',
-  ]);
+  await act(async () => {
+    await selectEvent.select(
+      screen.getByLabelText('overview.badges.format'),
+      'overview.badges.options.formats.url',
+    );
+  });
 
   expect(
     screen.getByText(
-      'host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=alert_status&token=foo',
+      `host/api/project_badges/measure?branch=branch-6.7&project=my-project&metric=${MetricKey.alert_status}&token=foo`,
     ),
   ).toBeInTheDocument();
 
-  await selectEvent.select(screen.getByLabelText('overview.badges.metric'), MetricKey.coverage);
+  await act(async () => {
+    await selectEvent.openMenu(screen.getByLabelText('overview.badges.metric'));
+  });
+  fireEvent.click(screen.getByText(MetricKey.coverage));
 
   expect(
     screen.getByText(
@@ -122,11 +117,15 @@ it('should update params', async () => {
   ).toBeInTheDocument();
 });
 
+async function appLoaded() {
+  await waitFor(() => expect(screen.queryByLabelText(`loading`)).not.toBeInTheDocument());
+}
+
 function renderProjectBadges(props: Partial<ProjectBadgesProps> = {}) {
   return renderComponent(
     <ProjectBadges
       branchLike={mockBranch()}
-      component={mockComponent({ key: 'foo', qualifier: ComponentQualifier.Project })}
+      component={mockComponent({ configuration: { showSettings: true } })}
       {...props}
     />,
   );