Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
How to mock an unexported function in javascript jest?

I have a module in my vuejs project that i want to test

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 want to test this behavior but I don't want it to actually redirect, so i want to mock submitForm with a simple jest.fn() so that i can check it's behaviour.

I tried to implement rewire using babel for ts but i can't get it to work with the new vue-cli 5.*. These babel packages also seem to be abandoned. Is there another way to test this beheviour?

my test at this point:

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 try to mock submitForm but this isn't the way to go, perhaps anyone else knows how to mock this correctly.

update: I'm currently also trying to just export the submitForm anyway even if it's not ment to be exported, but I can't get that to work either. since I have to mock only one named export and not the default export

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

With a little inspiration of @jonrsharpe i created a new test with the idee that i should not test private methods.

I still find it a little dirty but this is a way of testing that when I call my function that does a redirect using a POST call, that it actually does a submit and that it does have the right attributes in the form that was created.

I'm open for other opinions and ways of testing this, or of ways to redirect the user with a post to another application.

import postRedirect from "@/application/util/postRedirect";

describe("PostRedirect", () => {
  it("", () => {
    const mockSubmit = jest.fn();
    window.HTMLFormElement.prototype.submit = mockSubmit
    postRedirect("test", { foo: "bar", baz: "foo" });
    expect(mockSubmit).toBeCalled();

    // @ts-ignore
    const values = Array.from(new FormData(document.getElementsByTagName("form")[0] as HTMLFormElement));
    
    expect(values[0][0]).toBe("foo");
    expect(values[0][1]).toBe("bar");
    expect(values[1][0]).toBe("baz");
    expect(values[1][1]).toBe("foo");
  });
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda