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

165
Visualizações
how to create instance of class with jest

I am a beginner in writing tests and in jest also. I want to test that this function to be called and return the success promise. I write a unit test for function using jest. The function gets like parameter instance of class that I can't create because its constructor requires parameters that I haven't access. I have a lot of functions that have Session like parametrs. How can test function when you cant provide parametrs for it? Can I mock instance of class or function and handle it without parameter?

async initFlow(session: Session) {
    const nextAtomId = session.userInput.getParam('NEXT_ATOM');
    if (nextAtomId) {
        const nextAtom = await AtomManager.findActiveAtom(nextAtomId);
        if (!session.features.useTerms || ['beforeTerms', 'TermsAndConditions'].includes(nextAtom.type)) {
            return AtomProcessor.processAtom(session, nextAtom);
        }
    }

    const start = await AtomManager.getStartAtom(`${session.botId}`);
    if (!start) {
        throw new Error('Could not find start atom');
    }

    session.user = await UserManager.getGlobalUser(session); // getGlobalUser makes initUser under the hood.
    return AtomProcessor.processAtom(session, start);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can mock both AtomManager & UserManager and provide a mock session object when calling initFlow.

jest.mock("./path/to/AtomManager");
jest.mock("./path/to/UserManager");

it("works", async () => {
  const mockSession = {
    userInput: {
      getParam: jest.fn(),
    },
    botId: "123",
  };
  const mockUser = "user123";
  const mockStartAtom = "atom123";
  AtomManager.getStartAtom.mockResolveValue(mockStartAtom);
  UserManager.getGlobalUser.mockResolveValue(mockUser);

  await initFlow(mockSession);

  expect(mockSession.user).toBe(mockUser);
  expect(AtomManager.getStartAtom).toHaveBeenCalledTimes(1);
  expect(AtomManager.getStartAtom).toHaveBeenCalledWith(mockSession.botId);
  expect(UserManager.getGlobalUser).toHaveBeenCalledTimes(1);
  expect(UserManager.getGlobalUser).toHaveBeenCalledWith(mockSession);
  expect(AtomProcessor.processAtom).toHaveBeenCalledTimes(1);
  expect(AtomProcessor.processAtom).toHaveBeenCalledWith(mockSession, mockStartAtom);
});

The snippet above makes the following assertions:

  1. AtomManager.getStartAtom is called once and it's called with the mock botId.

  2. UserManager.getGlobalUser is called once and it's called with the mock session object.

  3. UserManager.getGlobalUser has successfully added the user property on the passed session object.

  4. AtomProcessor.processAtom is called once and it's called with the mock session and the mock start atom.

You can similarly the test other branches of code.

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