Testing a module in my vuejs project is what I'm currently focusing on.
import { getBaseUrl } from "@/application/api/baseUrl";
export default (
uri: string,
requestBody: Record<string, string | number>
): void => {
let form = document.createElement("form";
form.method = "POST";
form.action = `${getBaseUrl()}/${uri}`;
form = convertToFormData(form, requestBody);
submitForm(form);
};
function convertToFormData(
form: HTMLFormElement,
requestBody: Record<string, string | number>
) {
for (const [key, value] of Object.entries(requestBody)) {
const element = document.createElement("input");
element.name = key;
element.value = value.toString();
form.appendChild(element);
}
return form;
}
function submitForm(form: HTMLFormElement) {
document.body.appendChild(form);
form.submit();
}
I need to test the behavior without actually redirecting. To achieve this, I plan to mock submitForm
using jest.fn()
and then analyze its behavior.
I attempted to implement rewire with babel for ts, but it didn't work with the new vue-cli 5.*. The babel packages appear to be outdated. Are there other methods to test this behavior effectively?
Below is my current testing scenario:
import postRedirect from "@/application/util/postRedirect";
const submitFormMock = jest.fn();
jest.mock("@/application/util/postRedirect", () => ({
...jest.requireActual('@/application/util/postRedirect'),
submitForm: submitFormMock,
}));
describe("PostRedirect", () => {
it("", () => {
postRedirect("test", { foo: "bar", baz: "foo" });
expect(submitFormMock).toBeCalled();
const formDataObject = {} as Record<string, unknown>;
for (const [key, value] of new FormData(
submitFormMock.mock.calls[0][0]
).entries()) {
formDataObject[key] = value;
}
expect(formDataObject.foo).toBe("bar");
expect(formDataObject.baz).toBe("foo");
});
});
I tried mocking submitForm
, but that approach seems ineffective. Any suggestions on how to correctly mock this behavior would be appreciated.
Update: I'm also exploring the option of exporting submitForm even if it's not intended for export. However, I'm facing challenges with this approach as well, especially since I need to mock only one named export rather than the default export.