Tengo una función de la siguiente manera:
async foo() : Promise<Object> { if(...) throw new Error }¿Cómo se supone que debo probar que se arroja el error? Actualmente estoy haciendo esto:
it("testing for error thrown", async function () { expect(async() => await foo()).to.throw(Error) })Puede hacer algo como esto y, si se produce el error, la prueba fallará.
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' }) })Prueba esto:
it("testing for error thrown", async function () { await expect(foo()).rejects.toThrow(Error) })Como mencionaste chai-as-promised , usarías:
expect(promise).to.eventually.be.rejected
o:
promise.should.be.rejected
También hay un rejectedWith() que le permite especificar la clase/constructor de error.
Aquí hay una demostración:
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>