Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/hook tests #130

Merged
merged 11 commits into from
Jul 20, 2023
4 changes: 1 addition & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
node_modules/
packages/graph-explorer-proxy-server/node_modules/
packages/graph-explorer/node_modules/
**/node_modules/
31 changes: 22 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,34 @@
"author": "amazon",
"license": "Apache-2.0",
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.40.0",
"@typescript-eslint/parser": "^5.41.0",
"concurrently": "^7.5.0",
"eslint": "^7.32.0",
"eslint-plugin-react": "^7.31.10",
"@typescript-eslint/eslint-plugin": "^5.60.0",
"@typescript-eslint/parser": "^5.60.0",
"concurrently": "^8.2.0",
"eslint": "^8.43.0",
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-react-hooks": "^4.6.0",
"husky": "^8.0.0",
"lint-staged": "^13.0.3",
"prettier": "2.1.2",
"typescript": "^4.8.4"
"husky": "^8.0.3",
"lint-staged": "^13.2.2",
"prettier": "2.8.8",
"typescript": "^5.1.3"
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write"
]
},
"pnpm": {
"overrides": {
"json5@>=2.0.0 <2.2.2": ">=2.2.2",
"minimatch@<3.0.5": ">=3.0.5",
"loader-utils@>=2.0.0 <2.0.4": ">=2.0.4",
"webpack@>=5.0.0 <5.76.0": ">=5.76.0",
"decode-uri-component@<0.2.1": ">=0.2.1",
"yaml@>=2.0.0-5 <2.2.2": ">=2.2.2",
"vite@>=3.0.2 <3.2.7": ">=3.2.7",
"xml2js@<0.5.0": ">=0.5.0",
"semver@<7.5.2": ">=7.5.2"
}
}
}
15 changes: 13 additions & 2 deletions packages/graph-explorer/babel.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
module.exports = {
presets: [
"@babel/preset-env",
["@babel/preset-react", { runtime: "automatic" }],
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
'@babel/preset-react',
'@babel/preset-typescript',
],
plugins: [
'@babel/plugin-syntax-import-meta',
cubeddu marked this conversation as resolved.
Show resolved Hide resolved
],
};
27 changes: 24 additions & 3 deletions packages/graph-explorer/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,29 @@ import type { Config } from "jest";

const config: Config = {
verbose: true,
preset: "ts-jest",
testEnvironment: "jsdom",
preset: 'ts-jest',
testEnvironment: 'node',
moduleFileExtensions: ['js', 'json', 'ts', 'tsx'],
rootDir: 'src',
testRegex: '.test.ts$',
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
transformIgnorePatterns: [
"node_modules/(?!(swiper|dom7)/)",
"node_modules/(?!(react-dnd-html5-backend)/)"
],
coverageDirectory: '../coverage',
testPathIgnorePatterns: [
'<rootDir>/node_modules/'
],
collectCoverageFrom: [
'**/*.(t|j)s',
],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/packages/$1/src',
},
coverageReporters: ['text', 'lcov'],
};

export default config;
export default config;
3 changes: 3 additions & 0 deletions packages/graph-explorer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,10 @@
},
"devDependencies": {
"@babel/core": "^7.19.3",
"@babel/plugin-syntax-import-meta": "^7.10.4",
"@babel/preset-env": "^7.19.4",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.22.5",
"@react-aria/overlays": "3.9.1",
"@react-stately/radio": "^3.5.0",
"@react-types/button": "^3.6.1",
Expand Down Expand Up @@ -131,6 +133,7 @@
"husky": "^8.0.0",
"jest": "^28.1.3",
"jest-environment-jsdom": "^29.0.1",
"jest-localstorage-mock": "^2.4.26",
"lint-staged": "^13.0.3",
"prettier": "2.1.2",
"react-test-renderer": "^17.0.2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const fetchNeighbors = async (
rawIds: Map<string, "string" | "number">
): Promise<NeighborsResponse> => {
const idType = rawIds.get(req.vertexId) ?? "string";
const gremlinTemplate = oneHopTemplate({...req, idType});
const gremlinTemplate = oneHopTemplate({ ...req, idType });
const data = await gremlinFetch<RawOneHopRequest>(gremlinTemplate);

const verticesResponse =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ describe("Gremlin > edgesSchemaTemplate", () => {

expect(template).toBe(
'g.E().project("route","contain")' +
'.by(V().bothE("route").limit(1))' +
'.by(V().bothE("contain").limit(1))' +
".limit(1)"
'.by(V().bothE("route").limit(1))' +
'.by(V().bothE("contain").limit(1))' +
".limit(1)"
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import isErrorResponse from './isErrorResponse';

describe('isErrorResponse', () => {
it('should return true for error response', () => {
const errorResponse = {
code: 400,
detailedMessage: 'Detailed error message',
};

expect(isErrorResponse(errorResponse)).toBe(true);
});

it('should return false for non-error response', () => {
const nonErrorResponse = {
status: 200,
message: 'OK',
};

expect(isErrorResponse(nonErrorResponse)).toBe(false);
});

it('should return false for error-like response missing code', () => {
const errorLikeResponse = {
detailedMessage: 'Detailed error message',
};

expect(isErrorResponse(errorLikeResponse)).toBe(false);
});

it('should return false for error-like response missing detailedMessage', () => {
const errorLikeResponse = {
code: 400,
};

expect(isErrorResponse(errorLikeResponse)).toBe(false);
});
});
71 changes: 71 additions & 0 deletions packages/graph-explorer/src/hooks/useEntities.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import 'jest-localstorage-mock';
import { renderHook } from '@testing-library/react-hooks';
import { RecoilRoot, useSetRecoilState } from 'recoil';
import { useEffect } from 'react';
import useEntities from './useEntities';
import { nodesSelector } from '../core/StateProvider/nodes';
import { edgesSelector } from '../core/StateProvider/edges';
import { Edge, Vertex } from '../@types/entities';

jest.mock('localforage', () => ({
config: jest.fn(),
getItem: jest.fn(),
}));

const mockNode1 = {
data: {
id: 'node1',
type: 'Person',
neighborsCount: 2,
neighborsCountByType: {},
}
} as Vertex;

const mockNode2 = {
data: {
id: 'node2',
type: 'Organization',
neighborsCount: 1,
neighborsCountByType: {},
}
} as Vertex;

const mockEdge1 = {
data: {
id: "edge1",
type: "FRIEND",
source: "node1",
target: "node2",
}
} as Edge;

describe('useEntities', () => {
cubeddu marked this conversation as resolved.
Show resolved Hide resolved
it('returns expected values with default options', () => {
const nodes = [mockNode1, mockNode2];
const edges = [mockEdge1];

const { result } = renderHook(
() => {
// Set Recoil state to mock values
const setNodes = useSetRecoilState(nodesSelector);
const setEdges = useSetRecoilState(edgesSelector);

useEffect(() => {
setNodes(nodes);
setEdges(edges);
}, [setNodes, setEdges]);

return useEntities({ disableFilters: true });
},
{
wrapper: RecoilRoot,
}
);

expect(result.current[0]).toEqual({
nodes: [mockNode1, mockNode2],
edges: [mockEdge1],
});
});

});
69 changes: 69 additions & 0 deletions packages/graph-explorer/src/hooks/useEntitiesCounts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { renderHook } from "@testing-library/react-hooks";
import useEntitiesCounts from "./useEntitiesCounts";
import { useConfiguration } from "../core";

jest.mock("../core", () => ({
__esModule: true,
useConfiguration: jest.fn(),
}));

describe("useEntitiesCounts", () => {
beforeEach(() => {
jest.resetAllMocks();
});

it('returns total vertices when totalVertices is defined', () => {
(useConfiguration as jest.Mock).mockReturnValue({
id: 'some-id',
totalVertices: 10,
vertexTypes: ["type1", "type2"],
edgeTypes: ["edgeType1"],
getEdgeTypeConfig: jest.fn(() => ({ total: 5 }))
});

const { result } = renderHook(() => useEntitiesCounts());

expect(result.current.totalNodes).toEqual(10);
});

it('returns 0 for totalNodes when vertexTypes array is empty', () => {
(useConfiguration as jest.Mock).mockReturnValue({
id: 'some-id-two',
totalVertices: 0,
totalEdges: 0,
vertexTypes: [],
edgeTypes: ["edgeType1"],
});

const { result } = renderHook(() => useEntitiesCounts());

expect(result.current.totalNodes).toBe(0);
});

it('returns calculated total nodes when vertexTypes array is not empty and each type has a total', () => {
(useConfiguration as jest.Mock).mockReturnValue({
vertexTypes: ['type1', 'type2'],
edgeTypes: ['edgeType1', 'edgeType2'],
getVertexTypeConfig: jest.fn(() => ({ total: 5 })),
getEdgeTypeConfig: jest.fn(() => ({ total: 5 }))
});
const { result } = renderHook(() => useEntitiesCounts());

expect(result.current.totalNodes).toEqual(10);
});

it('returns totalNodes when vertexTypes array is not empty and at least one type does not have a total', () => {
(useConfiguration as jest.Mock).mockReturnValue({
vertexTypes: ['type1', 'type2'],
edgeTypes: ['edgeType1', 'edgeType2'],
getVertexTypeConfig: jest.fn(() => ({ total: 5 })),
getEdgeTypeConfig: jest.fn(() => ({ total: null }))
});

const { result } = renderHook(() => useEntitiesCounts());

expect(result.current.totalNodes).toBe(10);
});

});

55 changes: 55 additions & 0 deletions packages/graph-explorer/src/hooks/useNeighborsOptions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import 'jest-localstorage-mock';
import { renderHook } from '@testing-library/react-hooks';
import { useConfiguration } from '../core';
import useTextTransform from './useTextTransform';
import useNeighborsOptions from './useNeighborsOptions';
import { Vertex } from '../@types/entities';

jest.mock('../core/ConfigurationProvider/useConfiguration');
jest.mock('localforage');
jest.mock('./useTextTransform');

jest.mock('../core/ConfigurationProvider/ConfigurationProvider.tsx', () => ({
ConfigurationProvider: ({ children }: any) => children,
}));

jest.mock('../core/ConnectedProvider/ConnectedProvider.tsx', () => ({
ConnectedProvider: ({ children }: any) => children,
}));

describe('useNeighborsOptions', () => {
const vertex = {
data: {
neighborsCountByType: { nodeType1: 5, nodeType2: 3 },
__unfetchedNeighborCounts: { nodeType1: 0, nodeType2: 1 },
},
} as unknown as Vertex;

it('should return neighbors options correctly', () => {
// Mock return values for useConfiguration and useTextTransform

(useConfiguration as jest.Mock).mockReturnValue({
getVertexTypeConfig: (type: any) => {
return { displayLabel: `Label ${type}` };
},
});
(useTextTransform as jest.Mock).mockReturnValue((str: string) => str.toUpperCase());
cubeddu marked this conversation as resolved.
Show resolved Hide resolved

const { result } = renderHook(() => useNeighborsOptions(vertex),);

expect(result.current).toEqual([
{
label: 'Label nodeType1',
value: 'nodeType1',
isDisabled: true,
config: { displayLabel: 'Label nodeType1' },
},
{
label: 'Label nodeType2',
value: 'nodeType2',
isDisabled: false,
config: { displayLabel: 'Label nodeType2' },
},
]);
});
});
Loading