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

183
Visualizações
How to test for error thrown using chai or chai-as-promised for async functions?

I have a function as follows:

async foo() : Promise<Object> { 
   if(...) throw new Error
}

How am I supposed to test that the error is thrown? Currently I'm doing this:

it("testing for error thrown", async function () {
   expect(async() => await foo()).to.throw(Error)
})
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can do something like this and if the error is thrown, the test will fail.

const foo = async (): Promise<Object> => {
  // If you want the test to fail increase x to 11
  const x = 0
  if (x > 10) {
    throw Error('Test will fail')
  }
  // Add meaningful code this is just an example
  return { some: 'object' }
}

it('testing for error thrown', async () => {
  const object = await foo()
  expect(object).toEqual({ some: 'object' })
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Try this:

it("testing for error thrown", async function () {
   await expect(foo()).rejects.toThrow(Error)
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Since you mentioned chai-as-promised, you would use either:

expect(promise).to.eventually.be.rejected

or:

promise.should.be.rejected

There's also rejectedWith() which lets you specify the Error class/constructor.

Here's a demo:

mocha.setup('bdd');
mocha.checkLeaks();

let { expect } = chai;
chai.should();
let chaiAsPromised = module.exports; /* hack due to lack of UMD file, only for SO */
chai.use(chaiAsPromised);

async function foo(){ 
   throw new Error();
}

describe('Asynchronous Function', function(){
  it('Expect and Eventually', function(){
      return expect(foo()).to.eventually.be.rejected;
  })
  
  it('With Should', function(){
      return foo().should.be.rejected;
  });
});

mocha.run();
.as-console {
   display: none !important;
}
<script>
window.module = {}; function require(){ return {} }; /* hack due to lack of UMD file, only for SO */
</script>
<script src="https://cdn.jsdelivr.net/npm/chai-as-promised@7.1.1/lib/chai-as-promised.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/9.1.1/mocha.min.js"></script>
<script src="https://unpkg.com/chai@4.3.4/chai.js"></script>
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<div id="mocha"></div>

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