javascriptnode.jsmocha.jschaichai-as-promised

Assertion error when testing async function with mocha and chaiAsPromised


So i am trying to test that my async function throws an error when I stub s3GetObject = Promise.promisify(s3.getObject.bind(s3)) to be rejected with blah however i am getting that my function is not async and it does not throw an error.

below is my main.js file with the tests.js of this:

const Promise = require('bluebird');
const AWS = require('aws-sdk');

const s3 = new AWS.S3({
});

const s3GetObject = Promise.promisify(s3.getObject.bind(s3));

async function getS3File(){
  try {
    const contentType = await s3GetObject(s3Params);
    console.log('CONTENT:', contentType);
    return contentType;
  } catch (err) {
    console.log(err);
   throw new Error(err);
  }
};

Testing:

    /* eslint-env mocha */
const rewire = require('rewire');
const chai = require('chai');
const sinonChai = require('sinon-chai');
const sinon = require('sinon');
const chaiAsPromised = require('chai-as-promised');

chai.should();
chai.use(sinonChai);
chai.use(chaiAsPromised);

describe('Main', () => {

  describe('getFileFromS3', () => {
    let sut, getS3File, callS3Stub;

    beforeEach(() => {
      sut = rewire('../../main');
      getS3File = sut.__get__('getS3File');
      sinon.spy(console, 'log');
    });

    afterEach(() => {
      console.log.restore();
    });

    it('should be a function', () => {
      getS3File.should.be.a('AsyncFunction');
    });

    describe('with error', () => {
      beforeEach(() => {
        callS3Stub = sinon.stub().rejects('blah');
        sut.__set__('s3GetObject', callS3Stub);
        getS3File = sut.__get__('getS3File');
      });

      it('should error with blah', async () => {
        await getS3File.should.throw();
        //await console.log.should.be.calledWith('blah');

      });
    });
  });
});

The errors I am getting are: 1) Main

getFileFromS3 should be a function: AssertionError: expected [Function: getS3File] to be an asyncfunction at Context.it (test\unit\main.spec.js:28:27)

2) Main

getFileFromS3 with error should error with blah: AssertionError: expected [Function: getS3File] to throw an error

UnhandledPromiseRejectionWarning: Error: blah UnhandledPromiseRejectionWarning: Unhandled promise rejection.

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 228)


Solution

  • As explained in this answer, it doesn't matter whether a function is async or not, as long as it returns a promise. Chai relies on type-detect to detect types and detects async function as function.

    It should be:

    getS3File.should.be.a('function');
    

    async functions are syntactic sugar for promises, they don't throw errors but return rejected promises.

    It should be:

    getS3File().should.be.rejectedWith(Error);