Skip to content
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
101 changes: 101 additions & 0 deletions src/actions/__tests__/email-actions.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/**
* @jest-environment jsdom
*/
import configureStore from "redux-mock-store";
import thunk from "redux-thunk";
import flushPromises from "flush-promises";
import {
postRequest,
putRequest
} from "openstack-uicore-foundation/lib/utils/actions";
import { saveEmailTemplate } from "../email-actions";
import * as methods from "../../utils/methods";

jest.mock("openstack-uicore-foundation/lib/utils/actions", () => ({
__esModule: true,
...jest.requireActual("openstack-uicore-foundation/lib/utils/actions"),
postRequest: jest.fn(),
putRequest: jest.fn()
}));

jest.mock("../marketing-actions", () => ({
saveMarketingSetting: jest.fn()
}));

const requestMock =
(requestActionCreator, receiveActionCreator) => () => (dispatch) => {
if (requestActionCreator && typeof requestActionCreator === "function") {
dispatch(requestActionCreator({}));
}
return new Promise((resolve) => {
if (typeof receiveActionCreator === "function") {
dispatch(receiveActionCreator({ response: { id: 1 } }));
} else {
dispatch(receiveActionCreator);
}
resolve({ response: { id: 1 } });
});
};

describe("saveEmailTemplate", () => {
const middlewares = [thunk];
const mockStore = configureStore(middlewares);

beforeEach(() => {
jest.spyOn(methods, "getAccessTokenSafely").mockResolvedValue("TOKEN");
postRequest.mockImplementation(requestMock);
putRequest.mockImplementation(requestMock);
});

afterEach(() => {
jest.restoreAllMocks();
});

describe("create path (entity has no id)", () => {
it("returns a Promise", async () => {
const store = mockStore({});
const result = store.dispatch(
saveEmailTemplate({ identifier: "test-template" })
);
expect(result).toBeInstanceOf(Promise);
await expect(result).resolves.toBeUndefined();
});

it("dispatches TEMPLATE_ADDED then STOP_LOADING on success", async () => {
const store = mockStore({});
store.dispatch(saveEmailTemplate({ identifier: "test-template" }));
await flushPromises();

const actionTypes = store.getActions().map((a) => a.type);
expect(actionTypes).toContain("TEMPLATE_ADDED");
expect(actionTypes).toContain("STOP_LOADING");
expect(actionTypes.indexOf("STOP_LOADING")).toBeGreaterThan(
actionTypes.indexOf("TEMPLATE_ADDED")
);
});
});

describe("update path (entity has id)", () => {
it("returns a Promise", async () => {
const store = mockStore({});
const result = store.dispatch(
saveEmailTemplate({ id: 1, identifier: "test-template" })
);
expect(result).toBeInstanceOf(Promise);
await expect(result).resolves.toBeUndefined();
});

it("dispatches TEMPLATE_UPDATED then STOP_LOADING on success", async () => {
const store = mockStore({});
store.dispatch(saveEmailTemplate({ id: 1, identifier: "test-template" }));
await flushPromises();

const actionTypes = store.getActions().map((a) => a.type);
expect(actionTypes).toContain("TEMPLATE_UPDATED");
expect(actionTypes).toContain("STOP_LOADING");
expect(actionTypes.indexOf("STOP_LOADING")).toBeGreaterThan(
actionTypes.indexOf("TEMPLATE_UPDATED")
);
});
});
});
47 changes: 21 additions & 26 deletions src/actions/email-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,14 @@ import {
createAction,
stopLoading,
startLoading,
showMessage,
showSuccessMessage,
authErrorHandler,
fetchResponseHandler,
fetchErrorHandler,
escapeFilterValue
} from "openstack-uicore-foundation/lib/utils/actions";
import URI from "urijs";
import debounce from "lodash/debounce"
import history from "../history";
import debounce from "lodash/debounce";
import { checkOrFilter, getAccessTokenSafely } from "../utils/methods";
import { saveMarketingSetting } from "./marketing-actions";
import {
Expand Down Expand Up @@ -99,7 +97,7 @@ export const getEmailTemplates =
createAction(RECEIVE_TEMPLATES),
`${window.EMAIL_API_BASE_URL}/api/v1/mail-templates`,
authErrorHandler,
{ order, orderDir, term }
{ order, orderDir, term, page, perPage }
)(params)(dispatch).then(() => {
dispatch(stopLoading());
});
Expand Down Expand Up @@ -137,40 +135,37 @@ export const saveEmailTemplate =
const params = { access_token: accessToken, expand: "parent,versions" };

if (entity.id) {
putRequest(
return putRequest(
null,
createAction(TEMPLATE_UPDATED),
`${window.EMAIL_API_BASE_URL}/api/v1/mail-templates/${entity.id}`,
normalizedEntity,
customErrorHandler,
entity
)(params)(dispatch).then(() => {
if (!noAlert)
dispatch(showSuccessMessage(T.translate("emails.template_saved")));
else dispatch(stopLoading());
});
} else {
const success_message = {
title: T.translate("general.done"),
html: T.translate("emails.template_created"),
type: "success"
};

postRequest(
)(params)(dispatch)
.then(() => {
if (!noAlert)
dispatch(showSuccessMessage(T.translate("emails.template_saved")));
})
.finally(() => {
dispatch(stopLoading());
});
}
return postRequest(
null,
createAction(TEMPLATE_ADDED),
`${window.EMAIL_API_BASE_URL}/api/v1/mail-templates`,
normalizedEntity,
customErrorHandler,
entity
)(params)(dispatch).then((payload) => {
dispatch(
showMessage(success_message, () => {
history.push(`/app/emails/templates/${payload.response.id}`);
})
);
});
}
)(params)(dispatch)
.then(() => {
dispatch(showSuccessMessage(T.translate("emails.template_created")));
})
.finally(() => {
dispatch(stopLoading());
});

};

export const deleteEmailTemplate = (templateId) => async (dispatch) => {
Expand Down
110 changes: 110 additions & 0 deletions src/pages/emails/__tests__/email-template-list-page.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import React from "react";
import { act, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";
import flushPromises from "flush-promises";
import { renderWithRedux } from "../../../utils/test-utils";
import EmailTemplateListPage from "../email-template-list-page";
import {
getEmailTemplates,
deleteEmailTemplate
} from "../../../actions/email-actions";

jest.mock("../../../actions/email-actions", () => ({
getEmailTemplates: jest.fn(),
deleteEmailTemplate: jest.fn()
}));

jest.mock("openstack-uicore-foundation/lib/components/mui/table", () => ({
__esModule: true,
default: ({ onEdit, onDelete }) => (
<div>
<button
type="button"
onClick={() => onEdit({ id: 1, identifier: "test-template" })}
>
edit-row
</button>
<button
type="button"
onClick={() => onDelete({ id: 1, identifier: "test-template" })}
>
delete-row
</button>
</div>
)
}));

jest.mock(
"openstack-uicore-foundation/lib/components/mui/search-input",
() => ({
__esModule: true,
default: () => <input placeholder="search-templates" />
})
);

jest.mock("i18n-react/dist/i18n-react", () => ({
__esModule: true,
default: { translate: (key) => key }
}));

const mockHistory = { push: jest.fn() };

const initialState = {
emailTemplateListState: {
templates: [
{
id: 1,
identifier: "test-template",
subject: "Test Subject",
from_email: "test@example.com"
}
],
totalTemplates: 1,
perPage: 10,
currentPage: 1,
term: "",
order: "id",
orderDir: 1
}
};

describe("EmailTemplateListPage", () => {
beforeEach(() => {
jest.clearAllMocks();
getEmailTemplates.mockReturnValue(() => Promise.resolve());
deleteEmailTemplate.mockReturnValue(() => Promise.resolve());
});

it("reloads the list after a successful delete", async () => {
renderWithRedux(<EmailTemplateListPage history={mockHistory} />, {
initialState
});

await act(async () => {
await userEvent.click(screen.getByRole("button", { name: "delete-row" }));
await flushPromises();
});

// Call 1: useEffect on mount; call 2: handleDeleteEmailTemplate .finally()
expect(getEmailTemplates).toHaveBeenCalledTimes(2);
});

it("re-syncs the list after a failed delete", async () => {
deleteEmailTemplate.mockReturnValue(() =>
Promise.reject(new Error("delete failed"))
);

renderWithRedux(<EmailTemplateListPage history={mockHistory} />, {
initialState
});

await act(async () => {
await userEvent.click(screen.getByRole("button", { name: "delete-row" }));
await flushPromises();
});

// Call 1: useEffect on mount; call 2: handleDeleteEmailTemplate .finally() fires even on rejection
expect(getEmailTemplates).toHaveBeenCalledTimes(2);
});
});
Loading
Loading