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

Test/front end tests #158

Open
wants to merge 4 commits into
base: test/front_end_tests
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 97 additions & 3 deletions frontend/__tests__/unit/components/Bar.test.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { render } from "@testing-library/react";
import { render, screen } from "@testing-library/react";
import Bar from "components/Bar";
import { Router } from "react-router-dom";
import { MemoryRouter, Route, Router } from "react-router-dom";
import { createMemoryHistory } from "history";
import userEvent from "@testing-library/user-event";

// Useful reference: https://bholmes.dev/blog/mocking-browser-apis-fetch-localstorage-dates-the-easy-way-with-jest/

Expand All @@ -10,10 +11,10 @@ let mockStorage = {};
describe("Bar", () => {
beforeAll(() => {
global.Storage.prototype.getItem = jest.fn((key) => mockStorage[key]);
global.Storage.prototype.clear = jest.fn(() => (mockStorage = {}));
});

beforeEach(() => {
// make sure the fridge starts out empty for each test
mockStorage = {};
});

Expand Down Expand Up @@ -44,4 +45,97 @@ describe("Bar", () => {
);
expect(container).toMatchSnapshot();
});

it("renders Bar unchanged when logged in, after clicking button to open menu", async () => {
const history = createMemoryHistory();
const user = userEvent.setup();
mockStorage["loggedIn"] = true;

const { container } = render(
<Router history={history}>
<Bar />
</Router>
);

const menuButton = screen.getByRole("button", {
name: "",
});

await user.click(menuButton);

const logOutMenuItem = screen.getByRole("menuitem", {
name: "Log out",
});
expect(logOutMenuItem).toBeInTheDocument();

expect(container).toMatchSnapshot();
});

test("open and close menu when logged in", async () => {
const history = createMemoryHistory();
const user = userEvent.setup();
mockStorage["loggedIn"] = true;

render(
<Router history={history}>
<Bar />
</Router>
);

const menuButton = screen.getByRole("button", {
name: "",
});

// Open menu
await user.click(menuButton);

const logOutMenuItem = screen.getByRole("menuitem", {
name: "Log out",
});
expect(logOutMenuItem).toBeInTheDocument();

// Close menu
await user.keyboard("{Escape}");

expect(logOutMenuItem).not.toBeInTheDocument();
});

test("open menu and click on 'Log out'", async () => {
const user = userEvent.setup();
mockStorage["loggedIn"] = true;
let testLocation;

render(
<MemoryRouter initialEntries={["/test-url/"]}>
<Route path="/test-url">
<Bar />
</Route>
<Route
path="*"
render={({ location }) => {
testLocation = location;
return null;
}}
/>
</MemoryRouter>
);

const menuButton = screen.getByRole("button", {
name: "",
});

// Open menu
await user.click(menuButton);

const logOutMenuItem = screen.getByRole("menuitem", {
name: "Log out",
});
expect(logOutMenuItem).toBeInTheDocument();

// Click on 'Log out'
await user.click(logOutMenuItem);

expect(Object.keys(mockStorage).length).toBe(0);
expect(testLocation.pathname).toBe("/");
});
});
44 changes: 43 additions & 1 deletion frontend/__tests__/unit/components/HomeLoggedIn.test.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { render, screen } from "@testing-library/react";
import HomeLoggedIn from "components/HomeLoggedIn";
import { Router } from "react-router-dom";
import { MemoryRouter, Route, Router } from "react-router-dom";
import { createMemoryHistory } from "history";
import { testNetwork } from "../../data/network";
import userEvent from "@testing-library/user-event";
import API from "utils/API";
import { act } from "react-dom/test-utils";
import MockAdapter from "axios-mock-adapter";

describe("HomeLoggedIn", () => {
Expand Down Expand Up @@ -43,4 +45,44 @@ describe("HomeLoggedIn", () => {

expect(container).toMatchSnapshot();
});

it("creates a new network when the 'Create A Network' button is clicked", async () => {
jest.spyOn(Math, "random").mockReturnValue(0.5);
jest.spyOn(Date, "now").mockImplementation(() => 1487076708000);

let mock = new MockAdapter(API);
const user = userEvent.setup();
let testLocation;
const networkId = "testid";

// For the API call with the initial render
mock.onGet("network").reply(200, []);

// For the API call after the 'Create A Network' button is clicked
mock.onPost("/network").reply(200, { config: { id: "testid" } });

await act(async () => {
render(
<MemoryRouter initialEntries={["/"]}>
<Route path="/">
<HomeLoggedIn />
</Route>
<Route
path="*"
render={({ location }) => {
testLocation = location;
return null;
}}
/>
</MemoryRouter>
);
});

const createANetworkButton = screen.getByRole("button", {
name: "Create A Network",
});

await user.click(createANetworkButton);
expect(testLocation.pathname).toBe("/network/testid");
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,73 @@ exports[`Bar renders Bar unchanged when logged in 1`] = `
</div>
`;

exports[`Bar renders Bar unchanged when logged in, after clicking button to open menu 1`] = `
<div
aria-hidden="true"
>
<header
class="MuiPaper-root MuiAppBar-root MuiAppBar-positionStatic MuiAppBar-colorSecondary MuiPaper-elevation4"
style="background: rgb(0, 0, 0);"
>
<div
class="MuiToolbar-root MuiToolbar-regular MuiToolbar-gutters"
>
<div
class="MuiBox-root MuiBox-root-3"
>
<h6
class="MuiTypography-root MuiTypography-h6 MuiTypography-colorInherit"
>
<a
class="MuiTypography-root MuiLink-root MuiLink-underlineNone MuiTypography-colorInherit"
href="/"
>
<img
alt="logo"
height="100"
src="test-file-stub"
width="100"
/>
</a>
</h6>
</div>
<button
class="MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-colorInherit"
tabindex="0"
type="button"
>
<span
class="MuiButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"
/>
</svg>
</span>
<span
class="MuiTouchRipple-root"
>
<span
class="MuiTouchRipple-ripple MuiTouchRipple-rippleVisible"
style="width: 2.8284271247461903px; height: 2.8284271247461903px; top: -1.4142135623730951px; left: -1.4142135623730951px;"
>
<span
class="MuiTouchRipple-child MuiTouchRipple-childLeaving"
/>
</span>
</span>
</button>
</div>
</header>
</div>
`;

exports[`Bar renders Bar unchanged when logged out 1`] = `
<div>
<header
Expand Down
30 changes: 30 additions & 0 deletions frontend/__tests__/unit/utils/NetworkConfig.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as NetworkConfig from "utils/NetworkConfig";

jest.spyOn(Math, "random").mockReturnValue(0.5);
jest.spyOn(Date, "now").mockImplementation(() => 1487076708000);

describe("NetworkConfig", () => {
it("getRandomInt()", () => {
expect(NetworkConfig.getRandomInt(1, 10)).toBe(5);
expect(NetworkConfig.getRandomInt(2, 2)).toBe(2);
expect(NetworkConfig.getRandomInt("test", 10)).toBe(NaN);
expect(NetworkConfig.getRandomInt(1, "test")).toBe(NaN);
expect(NetworkConfig.getRandomInt("test", "test")).toBe(NaN);
});

it("generateNetworkConfig()", () => {
expect(NetworkConfig.generateNetworkConfig()).toStrictEqual({
config: {
name: "new-net-08000",
private: true,
v6AssignMode: { "6plane": false, rfc4193: false, zt: false },
v4AssignMode: { zt: true },
routes: [{ flags: 0, metric: 0, target: "172.30.127.0/24", via: null }],
ipAssignmentPools: [
{ ipRangeEnd: "172.30.127.254", ipRangeStart: "172.30.127.1" },
],
enableBroadcast: true,
},
});
});
});
3 changes: 2 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
"start": "BROWSER=none react-scripts start",
"build": "react-scripts build",
"analyze": "source-map-explorer 'build/static/js/*.js'",
"test:unit": "jest --coverage --testPathPattern='unit'"
"test:unit": "jest --coverage --testPathPattern='unit' --silent",
"test": "jest --coverage"
},
"homepage": "/app",
"proxy": "http://127.0.0.1:4000",
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/utils/NetworkConfig.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export function generateNetworkConfig() {
const randSubnetPart = getRandomInt(0, 254).toString();
const randNamePart = new Date().getTime();
const randNamePart = new Date(Date.now()).getTime();
return {
config: {
name: "new-net-" + randNamePart.toString().substring(8),
Expand All @@ -26,7 +26,7 @@ export function generateNetworkConfig() {
};
}

function getRandomInt(min, max) {
export function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
Expand Down