Skip to content

Commit 7ff9034

Browse files
Eisha KaushalEisha Kaushal
authored andcommitted
Backend unit tests
2 parents f7e4139 + 26059fe commit 7ff9034

27 files changed

+526
-200
lines changed
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
const { EcoTwoTone } = require('@material-ui/icons');
2+
const Chronos = require('../chronos_npm_package/chronos.js');
3+
const helpers = require('../chronos_npm_package/controllers/utilities.js');
4+
const hpropagate = require('hpropagate');
5+
const mongo = require('../chronos_npm_package/controllers/mongo.js');
6+
const postgres = require('../chronos_npm_package/controllers/postgres.js');
7+
8+
// Mock the utilities module functions
9+
jest.mock('../chronos_npm_package/controllers/utilities.js', () => ({
10+
validateInput: jest.fn(config => config),
11+
addNotifications: jest.fn(config => config),
12+
testMetricsQuery: jest.fn(config => config),
13+
getMetricsURI: jest.fn(config => config),
14+
}));
15+
16+
// mock propogate from Chronos
17+
jest.mock('hpropagate');
18+
19+
//mock fns found in track
20+
jest.mock('../chronos_npm_package/controllers/mongo.js', () => ({
21+
connect: jest.fn(config => config),
22+
services: jest.fn(config => config),
23+
docker: jest.fn(config => config),
24+
health: jest.fn(config => config),
25+
communications: jest.fn(config => config),
26+
serverQuery: jest.fn(config => config),
27+
}));
28+
29+
jest.mock('../chronos_npm_package/controllers/postgres.js', () => ({
30+
connect: jest.fn(config => config),
31+
services: jest.fn(config => config),
32+
docker: jest.fn(config => config),
33+
health: jest.fn(config => config),
34+
communications: jest.fn(config => config),
35+
serverQuery: jest.fn(config => config),
36+
}));
37+
38+
describe('Chronos Config', () => {
39+
afterEach(() => {
40+
// Clear mock function calls after each test
41+
jest.clearAllMocks();
42+
});
43+
44+
test('should throw an error if config is undefined', () => {
45+
expect(() => new Chronos()).toThrow('Chronos config is undefined');
46+
});
47+
48+
test('should call utilities functions with the correct parm', () => {
49+
const config = {
50+
microservice: 'test',
51+
interval: 300,
52+
mode: 'micro',
53+
dockerized: false,
54+
database: {
55+
connection: 'REST',
56+
type: process.env.CHRONOS_DB,
57+
URI: process.env.CHRONOS_URI,
58+
},
59+
notifications: [],
60+
};
61+
62+
const chronos = new Chronos(config);
63+
64+
// Ensure the config property is correctly set in the instance
65+
expect(chronos.config).toEqual(config);
66+
// Ensure the constructor called the validateInput and addNotifications functions
67+
expect(helpers.validateInput).toHaveBeenCalledWith(config);
68+
expect(helpers.addNotifications).toHaveBeenCalledWith(config);
69+
});
70+
71+
describe('propagate', () => {
72+
test('should check if propagate func properply calls hpropagate', () => {
73+
const config = {
74+
microservice: 'test',
75+
interval: 300,
76+
mode: 'micro',
77+
dockerized: false,
78+
database: {
79+
connection: 'REST',
80+
type: process.env.CHRONOS_DB,
81+
URI: process.env.CHRONOS_URI,
82+
},
83+
notifications: [],
84+
};
85+
86+
const chronos = new Chronos(config);
87+
chronos.propagate();
88+
expect(hpropagate).toHaveBeenCalledWith({ propagateInResponses: true });
89+
});
90+
});
91+
92+
describe('track', () => {
93+
test('should check if track function for MongoDB works', () => {
94+
//check if we can destructure database and dockerized from config
95+
const config = {
96+
microservice: 'test',
97+
interval: 300,
98+
mode: 'micro',
99+
dockerized: true,
100+
database: {
101+
connection: 'REST',
102+
type: 'MongoDB',
103+
URI: process.env.CHRONOS_URI,
104+
},
105+
notifications: [],
106+
};
107+
const { database, dockerized } = config;
108+
const falseDock = { dockerized: false };
109+
const chronos = new Chronos(config);
110+
chronos.track();
111+
if (database.type === 'MongoDB') {
112+
expect(mongo.connect).toHaveBeenCalledWith(config);
113+
expect(mongo.services).toHaveBeenCalledWith(config);
114+
if (dockerized) expect(mongo.docker).toHaveBeenCalledWith(config);
115+
if (!falseDock) expect(mongo.health).toHaveBeenCalledWith(config);
116+
if (database.connection === 'REST') expect(mongo.communications).not.toBeUndefined();
117+
}
118+
});
119+
test('should check if track function for Postgres works', () => {
120+
//check if we can destructure database and dockerized from config
121+
const config = {
122+
microservice: 'test',
123+
interval: 300,
124+
mode: 'micro',
125+
dockerized: true,
126+
database: {
127+
connection: 'REST',
128+
type: 'PostgreSQL',
129+
URI: process.env.CHRONOS_URI,
130+
},
131+
notifications: [],
132+
};
133+
const { database, dockerized } = config;
134+
const falseDock = { dockerized: false };
135+
const chronos = new Chronos(config);
136+
chronos.track();
137+
if (database.type === 'PostgreSQL') {
138+
expect(postgres.connect).toHaveBeenCalledWith(config);
139+
expect(postgres.services).toHaveBeenCalledWith(config);
140+
if (dockerized) expect(postgres.docker).toHaveBeenCalledWith(config);
141+
if (!falseDock) expect(postgres.health).toHaveBeenCalledWith(config);
142+
if (database.connection === 'REST') expect(postgres.communications).not.toBeUndefined();
143+
}
144+
});
145+
});
146+
describe('kafka', () => {
147+
test('should check if kafka is functional', async () => {
148+
const config = {
149+
microservice: 'test',
150+
interval: 300,
151+
mode: 'micro',
152+
dockerized: true,
153+
database: {
154+
connection: 'REST',
155+
type: 'MongoDB',
156+
URI: process.env.CHRONOS_URI,
157+
},
158+
notifications: [],
159+
};
160+
const { database, dockerized } = config;
161+
const falseDock = { dockerized: false };
162+
const chronos = new Chronos(config);
163+
chronos.kafka();
164+
await helpers.testMetricsQuery(config);
165+
if (database.type === 'MongoDB') {
166+
expect(mongo.connect).toHaveBeenCalledWith(config);
167+
expect(mongo.serverQuery).toHaveBeenCalledWith(config);
168+
}
169+
if (database.type === 'PostgreSQL') {
170+
expect(postgres.connect).toHaveBeenCalledWith(config);
171+
expect(postgres.serverQuery).toHaveBeenCalledWith(config);
172+
}
173+
});
174+
});
175+
176+
describe('kubernetes', () => {
177+
test('should check if kubernetes is functional', async () => {
178+
const config = {
179+
microservice: 'test',
180+
interval: 300,
181+
mode: 'micro',
182+
dockerized: true,
183+
database: {
184+
connection: 'REST',
185+
type: 'MongoDB',
186+
URI: process.env.CHRONOS_URI,
187+
},
188+
notifications: [],
189+
};
190+
const { database, dockerized } = config;
191+
const falseDock = { dockerized: false };
192+
const chronos = new Chronos(config);
193+
chronos.kubernetes();
194+
await helpers.testMetricsQuery(config);
195+
if (database.type === 'MongoDB') {
196+
expect(mongo.connect).toHaveBeenCalledWith(config);
197+
expect(mongo.serverQuery).toHaveBeenCalledWith(config);
198+
}
199+
if (database.type === 'PostgreSQL') {
200+
expect(postgres.connect).toHaveBeenCalledWith(config);
201+
expect(postgres.serverQuery).toHaveBeenCalledWith(config);
202+
}
203+
});
204+
});
205+
});

__backend-tests__/controllers/mongo.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ describe('mongo.connect', () => {
5959
beforeEach(() => {
6060
jest.clearAllMocks();
6161
});
62+
beforeEach(() => {
63+
jest.clearAllMocks();
64+
});
6265

6366
test('should connect to MongoDB database', async () => {
6467
await mongo.connect({ database: { URI: db } });
@@ -84,6 +87,9 @@ describe('mongo.services', () => {
8487
beforeEach(() => {
8588
jest.clearAllMocks();
8689
});
90+
beforeEach(() => {
91+
jest.clearAllMocks();
92+
});
8793

8894
afterEach(async () => {
8995
await dropCollections();

__backend-tests__/jest.config.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
module.exports = {
22
testEnvironment: 'node', // Use the Node.js environment for testing
3+
<<<<<<< HEAD
34
roots: ['<rootDir>/controllers'], // Set the root directory for test files
45

56
testRegex: '(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
@@ -12,3 +13,16 @@ module.exports = {
1213
testPathIgnorePatterns: ['/node_modules/', '/__tests__/'],
1314
};
1415

16+
=======
17+
roots: ['<rootDir>'], // Set the root directory for test files (adjust this path to your test folder)
18+
19+
testRegex: '(/tests/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
20+
21+
// Code coverage settings
22+
collectCoverage: true,
23+
coverageDirectory: 'coverage',
24+
25+
// Specify the test path patterns to ignore (frontend tests)
26+
testPathIgnorePatterns: ['/node_modules/', '/__tests__/'],
27+
};
28+
>>>>>>> dev

app/components/TransferColumns.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ const TransferColumns = React.memo(() => {
121121
const createSelectedMetricsList = () => {
122122
const temp: any[] = [];
123123
const categorySet = new Set();
124+
console.log('Inside TransferColumns.txs line 124 targetKeys: ', targetKeys)
124125
for (let i = 0; i < targetKeys.length; i++) {
125126
const str: string = targetKeys[i];
126127
const strArr: string[] = str.split(' | ');
@@ -191,6 +192,7 @@ const TransferColumns = React.memo(() => {
191192
color="primary"
192193
>
193194
Get Charts
195+
I'm in TransferColumns.txs line 194!
194196
</Button>
195197
</div>
196198
<div id="transferTest">

app/containers/GraphsContainer.tsx

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,7 @@ const GraphsContainer: React.FC = React.memo(props => {
4747

4848
useEffect(() => {
4949
const serviceArray = service.split(' ');
50-
// You would think you should add "kubernetesmetrics" into the below for consistency's sake but it makes it
51-
// not work correctly, so it has been omitted
50+
// You would think you should add "kubernetesmetrics" into the below for consistency's sake but it makes it not work correctly, so it has been omitted
5251
const healthServiceArray = serviceArray.filter((value: string) => value !== 'kafkametrics' && value !== 'kubernetesmetrics');
5352
if (live) {
5453
setIntervalID(
@@ -87,6 +86,7 @@ const GraphsContainer: React.FC = React.memo(props => {
8786
};
8887
}, [service, live]);
8988

89+
//random variable to hold the light or dark mode of the display?..ok....sure
9090
const currentMode = mode === 'light' ? lightAndDark.lightModeText : lightAndDark.darkModeText;
9191

9292
const routing = (route: string) => {
@@ -156,9 +156,10 @@ const GraphsContainer: React.FC = React.memo(props => {
156156
onClick={() => routing('all')}
157157
key="0"
158158
>
159-
Metrics Query
159+
Metrics Query onclick is not coming thru
160160
</button>
161161
{HealthAndEventButtons}
162+
<div font-color='white'>Here I am! in GraphsContainer.tsx!</div>
162163
{dockerData.containername && (
163164
<button
164165
id="docker-button"
@@ -208,6 +209,7 @@ const GraphsContainer: React.FC = React.memo(props => {
208209
{chart === 'all' && (
209210
<div className="transferColumns">
210211
<h2 style={currentMode}>Search Your Metrics to Display</h2>
212+
<div>THIS is LINE 212 in graphsContainer.tsx!!</div>
211213
<TransferColumns />
212214
</div>
213215
)}

app/context/ApplicationContext.tsx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
2525
const [savedMetrics, setSavedMetrics] = useState({});
2626
const [appIndex, setAppIndex] = useState<number>(0);
2727
const [intervalID, setIntervalID] = useState<NodeJS.Timeout | null>(null);
28-
28+
2929

3030
/**
3131
* @function fetchServicesNames - a function that will take an application name and update the state of `serviceData` based on backend response
@@ -34,7 +34,7 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
3434
* 3. Upon `servicesResponse`, parse the received JSON data and assign it to `servicesData`
3535
* 4. Remove the listener for `servicesResponse`
3636
* @param application - application name
37-
*/
37+
*/
3838
// v10: Invoked by connectToDB, passing in app (card title)
3939
const fetchServicesNames = useCallback((application: string) => {
4040
// console.log('Hi, inside ApplicationConext - fetchServicesNames callback. Sending servicesRequest to ipcMain.');
@@ -43,7 +43,7 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
4343
ipcRenderer.on('servicesResponse', (event: Electron.Event, data: any) => {
4444
let result: any;
4545
result = JSON.parse(data);
46-
// console.log('result from ipcrenderer services response is: ', result);
46+
console.log('result from ipcrenderer services response is: ', result);
4747
// console.log('Calling setServicesData passing in above result. Current servicesData is the following: ', servicesData);
4848
setServicesData(result);
4949
// console.log('Leaving fetchedServicesNames function.');
@@ -55,7 +55,7 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
5555
/**
5656
* @function connectToTB - invoked in Services Modal when Service Modal component is first rendered or when useEffect invoked.
5757
* creates an event emitter that connects to the user provided URI for the service (should be the database URI...)
58-
* v10 notes: seems to only be set up for local instances, not when a cloud based service is clicked, causes an issue since a user provided
58+
* v10 notes: seems to only be set up for local instances, not when a cloud based service is clicked, causes an issue since a user provided
5959
* database should not exist...
6060
* @params application - is the name of the card taht was clicked on
6161
*/
@@ -74,7 +74,7 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
7474

7575
/**
7676
* @function getSavedMetrics - a function that will wait for backend `savedMetricsResponse` to update metrics using `setSavedMetrics`
77-
* Trying to find what the data type needs to be.
77+
* Trying to find what the data type needs to be.
7878
*/
7979
const getSavedMetrics = useCallback(() => {
8080
ipcRenderer.send('savedMetricsRequest');
@@ -100,7 +100,7 @@ const ApplicationContextProvider: React.FC<AppContextProps> = React.memo(props =
100100
getSavedMetrics,
101101
setSavedMetrics,
102102
savedMetrics,
103-
appIndex,
103+
appIndex,
104104
setAppIndex,
105105
intervalID,
106106
setIntervalID,

app/context/DashboardContext.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ const DashboardContextProvider = React.memo((props: any) => {
4646
const [applications, setApplications] = useState<string[][]>([]);
4747
const [mode, setMode] = useState<string>('light');
4848

49-
49+
5050
const getApplications = useCallback(() => {
5151
const result = ipcRenderer.sendSync('getApps');
5252
setApplications(result);
@@ -64,7 +64,7 @@ const DashboardContextProvider = React.memo((props: any) => {
6464
// console.log('applications: ', applications);
6565
// console.log('new app to add: ', newApp);
6666
// setApplications([...applications, newApp]);
67-
// console.log('the current application that was added is : ', result);
67+
console.log('the current application that was added is : ', result);
6868
}, []);
6969

7070
const addAwsApp = useCallback((awsFields: AwsFields) => {

app/context/DockerContext.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ const DockerContextProvider: React.FC<Props> = React.memo((props) => {
3737

3838
ipcRenderer.on('dockerResponse', (data: any) => {
3939
let result;
40-
if (tryParseJSON(data)) result = JSON.parse(data);
40+
if (tryParseJSON(data)) {
41+
console.log('DockerContext.tsx line 41 result: ', result)
42+
result = JSON.parse(data);
43+
}
4144
const newDockerData = result[0] || {};
4245
console.log(newDockerData);
4346
setDockerData(newDockerData);

0 commit comments

Comments
 (0)