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

jest.mock("../../history", () => ({ push: jest.fn() }));

jest.mock("openstack-uicore-foundation/lib/utils/actions", () => ({
__esModule: true,
...jest.requireActual("openstack-uicore-foundation/lib/utils/actions"),
postRequest: jest.fn(),
putRequest: jest.fn(),
getRequest: jest.fn(),
deleteRequest: 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 } });
});
};

const getRequestMock =
(requestActionCreator, receiveActionCreator, _url, _handler, syncPayload) =>
() =>
(dispatch) => {
if (requestActionCreator && typeof requestActionCreator === "function") {
dispatch(requestActionCreator(syncPayload || {}));
}
return new Promise((resolve) => {
if (typeof receiveActionCreator === "function") {
dispatch(receiveActionCreator({ response: {} }));
} else {
dispatch(receiveActionCreator);
}
resolve({});
});
};

const deleteRequestMock =
(_requestActionCreator, receiveAction) => () => (dispatch) =>
new Promise((resolve) => {
if (typeof receiveAction === "function") {
dispatch(receiveAction({ response: {} }));
} else {
dispatch(receiveAction);
}
resolve({});
});

describe("saveEmailTemplate", () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file covers saveEmailTemplate only. Two other actions changed in this PR have no test coverage:

getEmailTemplates — the REQUEST payload now includes page and perPage for the first time (previously only order, orderDir, term). The reducer reads those fields to set currentPage and perPage state. Worth a test asserting the REQUEST_TEMPLATES action carries { page, perPage }:

describe('getEmailTemplates', () => {
  it('dispatches REQUEST_TEMPLATES with page and perPage', async () => {
    const store = mockStore({});
    store.dispatch(getEmailTemplates('foo', 2, 25));
    await flushPromises();
    const req = store.getActions().find(a => a.type === 'REQUEST_TEMPLATES');
    expect(req.payload).toMatchObject({ page: 2, perPage: 25 });
  });
});

deleteEmailTemplate — no test verifies that TEMPLATE_DELETED is dispatched with the correct templateId on a successful delete.

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")
);
});
});
});

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

beforeEach(() => {
jest.spyOn(methods, "getAccessTokenSafely").mockResolvedValue("TOKEN");
getRequest.mockImplementation(getRequestMock);
});

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

it("dispatches REQUEST_TEMPLATES with page and perPage", async () => {
const store = mockStore({});
store.dispatch(getEmailTemplates("foo", 2, 25));
await flushPromises();

const req = store.getActions().find((a) => a.type === "REQUEST_TEMPLATES");
expect(req.payload).toMatchObject({ page: 2, perPage: 25 });
});
});

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

beforeEach(() => {
jest.spyOn(methods, "getAccessTokenSafely").mockResolvedValue("TOKEN");
deleteRequest.mockImplementation(deleteRequestMock);
});

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

it("dispatches TEMPLATE_DELETED with the correct templateId", async () => {
const store = mockStore({});
store.dispatch(deleteEmailTemplate(42));
await flushPromises();

const deleted = store
.getActions()
.find((a) => a.type === "TEMPLATE_DELETED");
expect(deleted).toBeDefined();
expect(deleted.payload).toMatchObject({ templateId: 42 });
});
});
56 changes: 26 additions & 30 deletions src/actions/email-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +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 debounce from "lodash/debounce";
import history from "../history";
import { checkOrFilter, getAccessTokenSafely } from "../utils/methods";
import { saveMarketingSetting } from "./marketing-actions";
Expand Down Expand Up @@ -99,7 +98,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 +136,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(
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(() => {
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(showSuccessMessage(T.translate("emails.template_created")));
history.push(`/app/emails/templates/${payload.response.id}`);
})
.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