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

327
Visualizações
Jest: function that should throw does not pass and test will fail

I want to test a function A that calls multiple other functions inside it which can throw errors.

Here is an abstraction of my code:

// file A.ts

const A = (args: any[]): boolean => {

   (() => {
      // nested function which throws
      throw new RangeError("some arg not correct")
   })()

   return true
}

and

// file main.test.ts

test("should throw an error", () => {

   expect(A()).toThrow()

})

How do I test this appropriately in Jest?

The test won't succeed and jest will log the thrown error. Here is a sandbox and here is the output of the test you can see if you run test:

enter image description here

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

0

I'm not good with typescript so I have written the examples using regular JS.

It turns out you do not need to call the A function to test if it throws:

// throw.test.js
const A = () => {
  (() => {
    // nested function which throws
    throw new RangeError("some arg not correct")
  })();
};


test("should throw an error", () => {
  expect(A).toThrow();
})

which outputs

> jest
 PASS  ./throw.test.js
  ✓ should throw an error (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.404s
Ran all test suites.

If you do want to call the function, say to pass an argument, call it within another function that's passed to the expect:

// throw2.test.js
const A = () => {
  (() => {
    // nested function which throws
    throw new RangeError("some arg not correct")
  })();
};


test("should throw an error", () => {
  expect(() => A('my-arg')).toThrow();
})
about 4 years ago · Juan Pablo Isaza Relatório

0

I refactored a function that was async to no longer be async and was getting this error. So, if you have an inner-async function, use this approach:

test("async function throws", async() => {
    await expect(() => A('my-arg')).rejects.toThrow();
})

You can also do some more specific checks like, what kind of error and the message, etc.

test("async function throws", async() => {
    await expect(() => A('my-arg')).rejects.toThrow(MyError("Specific Error Message");
})
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