From 036ac907aec169dc2e68191bc53145aa698b2985 Mon Sep 17 00:00:00 2001 From: Eric Lavault <39483232+lvlte@users.noreply.github.com> Date: Mon, 11 Oct 2021 14:23:24 +0200 Subject: [PATCH] Graph2.js : Convert live test into Jest test. --- Data-Structures/Graph/Graph2.js | 32 ++---------------- Data-Structures/Graph/test/Graph2.test.js | 41 +++++++++++++++++++++++ 2 files changed, 44 insertions(+), 29 deletions(-) create mode 100644 Data-Structures/Graph/test/Graph2.test.js diff --git a/Data-Structures/Graph/Graph2.js b/Data-Structures/Graph/Graph2.js index 3d9873759..9defc1438 100644 --- a/Data-Structures/Graph/Graph2.js +++ b/Data-Structures/Graph/Graph2.js @@ -36,7 +36,7 @@ class Graph { } // Prints the vertex and adjacency list - printGraph () { + printGraph (output = value => console.log(value)) { // get all the vertices const getKeys = this.AdjList.keys() @@ -54,35 +54,9 @@ class Graph { } // print the vertex and its adjacency list - console.log(i + ' -> ' + conc) + output(i + ' -> ' + conc) } } } -// Example -const graph = new Graph(6) -const vertices = ['A', 'B', 'C', 'D', 'E', 'F'] -// adding vertices -for (let i = 0; i < vertices.length; i++) { - graph.addVertex(vertices[i]) -} - -// adding edges -graph.addEdge('A', 'B') -graph.addEdge('A', 'D') -graph.addEdge('A', 'E') -graph.addEdge('B', 'C') -graph.addEdge('D', 'E') -graph.addEdge('E', 'F') -graph.addEdge('E', 'C') -graph.addEdge('C', 'F') - -// prints all vertex and -// its adjacency list -// A -> B D E -// B -> A C -// C -> B E F -// D -> A E -// E -> A D F C -// F -> E C -graph.printGraph() +export { Graph } diff --git a/Data-Structures/Graph/test/Graph2.test.js b/Data-Structures/Graph/test/Graph2.test.js new file mode 100644 index 000000000..91473214e --- /dev/null +++ b/Data-Structures/Graph/test/Graph2.test.js @@ -0,0 +1,41 @@ +import { Graph } from '../Graph2' + +describe('Test Graph2', () => { + const vertices = ['A', 'B', 'C', 'D', 'E', 'F'] + const graph = new Graph(vertices.length) + + // adding vertices + for (let i = 0; i < vertices.length; i++) { + graph.addVertex(vertices[i]) + } + + // adding edges + graph.addEdge('A', 'B') + graph.addEdge('A', 'D') + graph.addEdge('A', 'E') + graph.addEdge('B', 'C') + graph.addEdge('D', 'E') + graph.addEdge('E', 'F') + graph.addEdge('E', 'C') + graph.addEdge('C', 'F') + + it('Check adjacency lists', () => { + const mockFn = jest.fn() + graph.printGraph(mockFn) + + // Expect one call per vertex + expect(mockFn.mock.calls.length).toBe(vertices.length) + + // Collect adjacency lists from output (call args) + const adjListArr = mockFn.mock.calls.map(v => v[0]) + + expect(adjListArr).toEqual([ + 'A -> B D E ', + 'B -> A C ', + 'C -> B E F ', + 'D -> A E ', + 'E -> A D F C ', + 'F -> E C ' + ]) + }) +})