Skip to content

Commit

Permalink
Fix tests after vitest migration
Browse files Browse the repository at this point in the history
  • Loading branch information
grahamalama committed Jan 12, 2024
1 parent 44ebe3a commit a054b1a
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 121 deletions.
67 changes: 24 additions & 43 deletions test/components/signoff/SimpleReview/SimpleReview_test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,8 @@ import React from "react";
import { fireEvent, waitForElementToBeRemoved } from "@testing-library/react";
import { renderWithProvider, sessionFactory } from "../../../test_utils";
import SimpleReview from "../../../../src/components/signoff/SimpleReview";
import { useLocalStorage } from "../../../../src/hooks/storage";
import { Redirect, useHistory } from "react-router-dom";
import { createMemoryHistory } from "history/";

vi.mock("../../../../src/hooks/storage", () => {
const originalModule = vi.importActual("../../../../src/hooks/storage");
return {
__esModule: true,
...originalModule,
useLocalStorage: vi.fn().mockReturnValue([true, vi.fn()]),
};
});

vi.mock("react-router-dom", () => {
const originalModule = vi.importActual("react-router-dom");
const pushMock = vi.fn();
const useHistory = () => {
return {
push: pushMock,
};
};
return {
__esModule: true,
...originalModule,
useHistory,
Redirect: vi.fn().mockReturnValue(<div>foo</div>),
};
});

vi.mock("../../../../src/permission", () => {
return {
Expand All @@ -38,6 +13,8 @@ vi.mock("../../../../src/permission", () => {
};
});

const rollbackChangesMock = vi.fn()

vi.mock("../../../../src/components/signoff/utils", () => {
return {
isMember: () => {
Expand Down Expand Up @@ -85,24 +62,25 @@ function signoffFactory() {
};
}

function renderSimpleReview(props = null) {
function renderSimpleReview(props = null, renderProps = {}) {
const mergedProps = {
match: {
params: {
bid: "main-workspace",
cid: "my-collection",
},
},
listRecords() {},
listRecords() { },
session: sessionFactory(),
signoff: signoffFactory(),
async fetchRecords() {
return [];
},
...props,
rollbackChanges: vi.fn(),
rollbackChanges: rollbackChangesMock,

};
return renderWithProvider(<SimpleReview {...mergedProps} />);
return renderWithProvider(<SimpleReview {...mergedProps} />, { ...renderProps });
}

const fakeLocation = {
Expand All @@ -112,6 +90,10 @@ const fakeLocation = {
};

describe("SimpleTest component", () => {
beforeEach(async () => {
localStorage.setItem("useSimpleReview", true)
})

it("should render spinner when authenticating", async () => {
const node = renderSimpleReview({
session: sessionFactory({ authenticated: false, authenticating: true }),
Expand Down Expand Up @@ -148,19 +130,18 @@ describe("SimpleTest component", () => {
});

it("should render a review component after records are fetched and allow for a rollback", async () => {
let node = renderSimpleReview({
async fetchRecords() {
return [];
},
});
await waitForElementToBeRemoved(() => node.queryByTestId("spinner"));
const history = createMemoryHistory({ initialEntries: ["/"] })
let node = renderSimpleReview(null, { initialHistory: history });
const historyPushSpy = vi.spyOn(history, "push")

expect(node.findByTestId(".simple-review-header")).toBeDefined();
await waitForElementToBeRemoved(() => node.queryByTestId("spinner"));
expect(await node.findByTestId("simple-review-header")).toBeDefined();

// also check rollback calls history.push while we're here
fireEvent.click(node.queryByText(/Rollback changes/));
fireEvent.click(node.queryByText("Rollback"));
expect(useHistory().push).toHaveBeenCalled();
expect(rollbackChangesMock).toHaveBeenCalled()
expect(historyPushSpy).toHaveBeenCalled()
});

it("should hide the rollback button if the hideRollback query parameter is provided", async () => {
Expand Down Expand Up @@ -211,12 +192,12 @@ describe("SimpleTest component", () => {
});

it("should redirect the user if the legacy review process is enabled", async () => {
useLocalStorage.mockReturnValue([false, vi.fn()]);
localStorage.setItem("useSimpleReview", false)
const session = sessionFactory();
session.serverInfo.user.principals = [];
renderSimpleReview({
session,
});
expect(Redirect).toHaveBeenCalled();
let node = renderSimpleReview({ session });

// Since Simple Review is the default, this means we're in the legacy UI
expect(node.queryByText("Switch to Default Review UI")).toBeDefined()
});
});
15 changes: 5 additions & 10 deletions test/components/signoff/components_test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,6 @@ import React from "react";
import { fireEvent } from "@testing-library/react";
import { renderWithProvider } from "../../test_utils";

vi.mock("../../../src/hooks/storage", () => {
const originalModule = vi.importActual("../../../src/hooks/storage");
return {
__esModule: true,
...originalModule,
useLocalStorage: vi.fn().mockReturnValue([false, vi.fn()]),
};
});

describe("SignoffToolBar component", () => {
const props = {
sessionState: {
Expand Down Expand Up @@ -127,10 +118,14 @@ describe("SignoffToolBar component", () => {
},
approveChanges: vi.fn(),
};

localStorage.setItem("useSimpleReview", false);

const node = renderWithProvider(<SignoffToolBar {...propsOverride} />);
expect(node.queryByTestId("spinner")).toBeNull();
expect(propsOverride.approveChanges).toHaveBeenCalledTimes(0);
fireEvent.click(await node.findByText("Approve"));
const approveButton = (await node.findByText("Approve"))
fireEvent.click(approveButton);
expect(await node.findByTestId("spinner")).toBeDefined();
expect(propsOverride.approveChanges).toHaveBeenCalledTimes(1);
});
Expand Down
24 changes: 0 additions & 24 deletions test/hooks/storage_test.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,6 @@
import { renderHook, act } from "@testing-library/react-hooks";
import { useLocalStorage } from "../../src/hooks/storage";

class localStorageClass {
isConstructor() {
this.store = {};
}

clear() {
this.store = {};
}

getItem(key) {
return this.store[key];
}

setItem(key, value) {
this.store[key] = String(value);
}

removeItem(key) {
delete this.store[key];
}
}

global.localStorage = new localStorageClass();

describe("useLocalStorage", () => {
it("should return default value if a value isn't set yet", () => {
const { result } = renderHook(() =>
Expand Down
18 changes: 8 additions & 10 deletions test/sagas/session_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,15 +179,15 @@ describe("session sagas", () => {
describe("setupSession()", () => {
let setupSession, getState, action;

const serverInfo = {
let serverInfo = {
...DEFAULT_SERVERINFO,
url: "http://server.test/v1",
user: {
id: "basicauth:abcd",
},
};

const sessionState = { serverInfo };
let sessionState = { serverInfo };

beforeAll(() => {
resetClient();
Expand Down Expand Up @@ -238,27 +238,25 @@ describe("session sagas", () => {
)
);
});

it("should correctly authenticate the user when using openID", () => {
vi.spyOn(serversActions, "addServer");
const authData = {
server: "http://server.test/v1",
authType: "openid-google",
credentials: { token: "the token" },
};
const serverInfo = {
serverInfo = {
...serverInfo,
user: { id: "google:token" },
url: "test-url",
};

const getStateOpenID = () => ({
session: {
serverInfo,
},
const sessionState = { serverInfo };
getState = () => ({
session: sessionState,
});

const action = actions.setupSession(authData);
const setupSession = saga.setupSession(getStateOpenID, action);
const setupSession = saga.setupSession(getState, action);
setupSession.next();
expect(setupSession.next(serverInfo).value).toStrictEqual(
put(actions.setAuthenticated())
Expand Down
29 changes: 12 additions & 17 deletions test/sagas/signoff_test.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,11 @@
import { call, put } from "redux-saga/effects";
import { notifySuccess, notifyError } from "../../src/actions/notifications";
import * as notificationActions from "../../src/actions/notifications";
import { routeLoadSuccess } from "../../src/actions/route";
import { setClient } from "../../src/client";
import * as actions from "../../src/actions/signoff";
import * as collection_actions from "../../src/actions/collection";
import * as saga from "../../src/sagas/signoff";

vi.mock("../../src/actions/notifications", () => {
const original = vi.importActual("../../src/actions/notifications");
return {
...original,
notifyError: vi.fn(),
};
});

describe("Signoff sagas", () => {
describe("list hook", () => {
let getState;
Expand Down Expand Up @@ -224,6 +216,7 @@ describe("Signoff sagas", () => {
});
vi.spyOn(console, "warn");
vi.spyOn(console, "error");
const notifyErrorSpy = vi.spyOn(notificationActions, "notifyError");
const action = collection_actions.listRecords(
"stage",
"source-plugins",
Expand All @@ -233,10 +226,10 @@ describe("Signoff sagas", () => {
expect(result.next().value).toBeUndefined();
expect(console.warn).toHaveBeenCalledTimes(1);
expect(console.error).toHaveBeenCalledTimes(0);
expect(notifyError).toHaveBeenCalledTimes(0);
expect(notifyErrorSpy).toHaveBeenCalledTimes(0);
});

it("Should catch and log an error if an error (not 401) response is received", () => {
it.only("Should catch and log an error if an error (not 401) response is received", () => {
vi.spyOn(actions, "workflowInfo").mockImplementation(() => {
const err = new Error("Test error");
err.data = {
Expand All @@ -246,6 +239,7 @@ describe("Signoff sagas", () => {
});
vi.spyOn(console, "warn");
vi.spyOn(console, "error");
const notifyErrorSpy = vi.spyOn(notificationActions, "notifyError");
const action = collection_actions.listRecords(
"stage",
"source-plugins",
Expand All @@ -254,8 +248,9 @@ describe("Signoff sagas", () => {
const result = saga.onCollectionRecordsRequest(getState, action);
expect(result.next().value).toBeUndefined();
expect(console.warn).toHaveBeenCalledTimes(0);
expect(console.error).toHaveBeenCalledTimes(1);
expect(notifyError).toHaveBeenCalledTimes(1);
// console.error called once in `onCollectionRecordsRequest`, and once in `notifyError`
expect(console.error).toHaveBeenCalledTimes(2);
expect(notifyErrorSpy).toHaveBeenCalledTimes(1);
});
});
});
Expand Down Expand Up @@ -335,7 +330,7 @@ describe("Signoff sagas", () => {

it("should dispatch a success notification", () => {
expect(handleRequestReview.next().value).toStrictEqual(
put(notifySuccess("Review requested."))
put(notificationActions.notifySuccess("Review requested."))
);
});
});
Expand Down Expand Up @@ -393,7 +388,7 @@ describe("Signoff sagas", () => {

it("should dispatch a success notification", () => {
expect(handleDeclineChanges.next().value).toStrictEqual(
put(notifySuccess("Changes declined."))
put(notificationActions.notifySuccess("Changes declined."))
);
});
});
Expand Down Expand Up @@ -448,7 +443,7 @@ describe("Signoff sagas", () => {

it("should dispatch a success notification", () => {
expect(handleApproveChanges.next().value).toStrictEqual(
put(notifySuccess("Signature requested."))
put(notificationActions.notifySuccess("Signature requested."))
);
});
});
Expand Down Expand Up @@ -506,7 +501,7 @@ describe("Signoff sagas", () => {

it("should dispatch a success notification", () => {
expect(handleRollbackChanges.next().value).toStrictEqual(
put(notifySuccess("Changes were rolled back."))
put(notificationActions.notifySuccess("Changes were rolled back."))
);
});
});
Expand Down
32 changes: 15 additions & 17 deletions test/utils_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -411,28 +411,26 @@ describe("diffJson", function () {
});

describe("getServerByPriority", () => {
const servers = [
{ server: "someServer", authType: ANONYMOUS_AUTH },
{ server: "otherServer", authType: ANONYMOUS_AUTH },
];
beforeEach(() => {
vi.resetModules();
});
it("should return SINGLE_SERVER", () => {
vi.doMock("../src/constants", () => {
const actual = vi.importActual("../src/constants");
return {
__esModule: true,
...actual,
SINGLE_SERVER: "http://www.example.com/",
};
});
const {
getServerByPriority: _getServerByPriority,
} = require("../src/utils");
expect(_getServerByPriority(servers)).toBe("http://www.example.com/");

it("should return SINGLE_SERVER", async () => {
vi.doMock("../src/constants", () => ({
get SINGLE_SERVER() {
return "http://www.example.com/";
},
}));
const { getServerByPriority: _getServerByPriority } = await import(
"../src/utils"
);
expect(_getServerByPriority([])).toBe("http://www.example.com/");
});
it("should return the first server from the array", () => {
const servers = [
{ server: "someServer", authType: ANONYMOUS_AUTH },
{ server: "otherServer", authType: ANONYMOUS_AUTH },
];
const server = getServerByPriority(servers);
expect(server).toBe("someServer");
});
Expand Down

0 comments on commit a054b1a

Please sign in to comment.