Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
vtsvetkov-splunk committed Jun 5, 2024
1 parent 370fa8b commit 32e2cf4
Show file tree
Hide file tree
Showing 7 changed files with 125 additions and 22 deletions.
26 changes: 23 additions & 3 deletions ui/src/components/ConfigurationFormView.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { _ } from '@splunk/ui-utils/i18n';
import styled from 'styled-components';
import WaitSpinner from '@splunk/react-ui/WaitSpinner';

import axios from 'axios';
import BaseFormView from './BaseFormView/BaseFormView';
import { StyledButton } from '../pages/EntryPageStyle';
import { axiosCallWrapper } from '../util/axiosCallWrapper';
Expand All @@ -24,15 +25,34 @@ function ConfigurationFormView({ serviceName }) {
const [currentServiceState, setCurrentServiceState] = useState({});

useEffect(() => {
const abortController = new AbortController();
axiosCallWrapper({
serviceName: `settings/${serviceName}`,
handleError: true,
signal: abortController.signal,
callbackOnError: (err) => {
if (abortController.signal.aborted) {
return;
}
setError(err);
},
}).then((response) => {
setCurrentServiceState(response.data.entry[0].content);
});
})
.catch((caughtError) => {
if (axios.isCancel(caughtError)) {
return null;
}
throw caughtError;
})
.then((response) => {
if (!response) {
return;
}
setCurrentServiceState(response.data.entry[0].content);
});

return () => {
abortController.abort();
};
}, [serviceName]);

/**
Expand Down
11 changes: 5 additions & 6 deletions ui/src/components/MultiInputComponent/MultiInputComponent.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import React, { useState, useEffect, ReactElement } from 'react';
import Multiselect from '@splunk/react-ui/Multiselect';
import styled from 'styled-components';
import axios from 'axios';
import WaitSpinner from '@splunk/react-ui/WaitSpinner';

import { axiosCallWrapper } from '../../util/axiosCallWrapper';
import { AxiosCallType, axiosCallWrapper } from '../../util/axiosCallWrapper';
import { filterResponse } from '../../util/util';

const MultiSelectWrapper = styled(Multiselect)`
Expand Down Expand Up @@ -84,15 +83,15 @@ function MultiInputComponent(props: MultiInputComponentProps) {
}

let current = true;
const source = axios.CancelToken.source();
const abortController = new AbortController();

const apiCallOptions = {
cancelToken: source.token,
signal: abortController.signal,
handleError: true,
params: { count: -1 },
serviceName: '',
endpointUrl: '',
};
} satisfies AxiosCallType;
if (referenceName) {
apiCallOptions.serviceName = referenceName;
} else if (endpointUrl) {
Expand Down Expand Up @@ -123,7 +122,7 @@ function MultiInputComponent(props: MultiInputComponentProps) {
}
// eslint-disable-next-line consistent-return
return () => {
source.cancel('Operation canceled.');
abortController.abort('Operation canceled.');
current = false;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
4 changes: 2 additions & 2 deletions ui/src/components/UCCCredit/UCCCredit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ const StyledTypography = styled(Typography)`
const UccCredit = () => {
const unifiedConfigs = getUnifiedConfigs();

// eslint-disable-next-line no-underscore-dangle
const uccVersion = unifiedConfigs?.meta?._uccVersion ?? null;
if (unifiedConfigs?.meta?.hideUCCVersion) {
return null;
}
// eslint-disable-next-line no-underscore-dangle
const uccVersion = unifiedConfigs?.meta?._uccVersion ?? null;
return (
<StyledTypography
as="span"
Expand Down
21 changes: 17 additions & 4 deletions ui/src/components/table/TableWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,33 +103,46 @@ function TableWrapper({
};

const fetchInputs = () => {
const abortController = new AbortController();

const requests =
services?.map((service) =>
axiosCallWrapper({
serviceName: service.name,
params: { count: -1 },
signal: abortController.signal,
})
) || [];

axios
.all(requests)
.catch((caughtError) => {
if (axios.isCancel(caughtError)) {
return;
}
const message = parseErrorMsg(caughtError);

generateToast(message, 'error');
setLoading(false);
setError(caughtError);
return Promise.reject(caughtError);
})
.then((response) => {
if (!response) {
return;
}
modifyAPIResponse(response.map((res) => res.data.entry));
});

return () => {
abortController.abort();
};
};

useEffect(() => {
fetchInputs();
useEffect(
() => fetchInputs(),
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
[]
);

/**
*
Expand Down
1 change: 1 addition & 0 deletions ui/src/mocks/server-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const mockServerResponseWithContent = {
updated: '2023-08-21T11:54:12+00:00',
entry: [
{
id: 1,
content: {
disabled: true,
},
Expand Down
70 changes: 70 additions & 0 deletions ui/src/pages/Configuration/ConfigurationPage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import * as React from 'react';
import { render } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';

import { http, HttpResponse } from 'msw';
import ConfigurationPage from './ConfigurationPage';
import { getUnifiedConfigs } from '../../util/util';
import { getGlobalConfigMock } from '../../mocks/globalConfigMock';
import { type meta as metaType } from '../../types/globalConfig/meta';
import { mockServerResponseWithContent } from '../../mocks/server-response';
import { server } from '../../mocks/server';

const mockNavigateFn = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigateFn,
}));

jest.mock('../../util/util');

const getUnifiedConfigsMock = getUnifiedConfigs as jest.Mock;

beforeEach(() => {
server.use(
http.get(`/servicesNS/nobody/-/:endpointUrl`, () =>
HttpResponse.json(mockServerResponseWithContent)
)
);
});

function setup(meta: Partial<metaType>) {
const globalConfigMock = getGlobalConfigMock();

getUnifiedConfigsMock.mockImplementation(() => ({
...globalConfigMock,
meta: {
...globalConfigMock.meta,
...meta,
},
}));
return render(<ConfigurationPage />, { wrapper: BrowserRouter });
}

it('should show UCC label', async () => {
const page = setup({
_uccVersion: undefined,
});

const uccLink = page.getByRole('link', { name: /ucc/i });
expect(uccLink).toBeInTheDocument();
expect(uccLink.getAttribute('href')).toContain('github.io');
});

it('should not show UCC label', async () => {
const page = setup({
hideUCCVersion: true,
});

const uccLink = page.queryByRole('link', { name: /ucc/i });
expect(uccLink).toBeNull();
});

it('should show UCC version', async () => {
const uccVersion = '5.2221.2341';
const page = setup({
_uccVersion: uccVersion,
});

expect(page.getByTestId('ucc-credit')).toHaveTextContent(uccVersion);
});
14 changes: 7 additions & 7 deletions ui/src/util/axiosCallWrapper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import axios, { CancelToken } from 'axios';
import axios, { AxiosRequestConfig } from 'axios';
import { CSRFToken, app } from '@splunk/splunk-utils/config';
import { createRESTURL } from '@splunk/splunk-utils/url';
import { generateEndPointUrl, generateToast } from './util';
Expand All @@ -16,15 +16,15 @@ interface axiosCallWithEndpointUrl {

interface CommonAxiosCall {
params?: Record<string, string | number>;
cancelToken?: CancelToken;
signal?: AbortSignal;
customHeaders?: Record<string, string>;
method?: 'get' | 'post' | 'delete';
body?: URLSearchParams;
handleError?: boolean;
callbackOnError?: (error: unknown) => void;
}

type AxiosCallType = (axiosCallWithServiceName | axiosCallWithEndpointUrl) & CommonAxiosCall;
export type AxiosCallType = (axiosCallWithServiceName | axiosCallWithEndpointUrl) & CommonAxiosCall;

/**
*
Expand All @@ -44,7 +44,7 @@ const axiosCallWrapper = ({
endpointUrl,
params,
body,
cancelToken,
signal,
customHeaders = {},
method = 'get',
handleError = false,
Expand Down Expand Up @@ -72,10 +72,10 @@ const axiosCallWrapper = ({
params: newParams,
method,
url,
credentials: 'include',
withCredentials: true,
headers,
cancelToken,
};
signal,
} satisfies AxiosRequestConfig;

if (method === 'post') {
options.data = body;
Expand Down

0 comments on commit 32e2cf4

Please sign in to comment.