使用 mocha 和 chaiAsPromised 测试异步函数时出现断言错误

Assertion error when testing async function with mocha and chaiAsPromised

所以我试图测试当我将 s3GetObject = Promise.promisify(s3.getObject.bind(s3)) 存根以被 blah 拒绝时我的异步函数是否抛出错误但是我得到我的函数不是异步的并且它不会抛出一个错误。

下面是我的 main.js 文件,其中包含 tests.js

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);
  }
};

测试:

    /* 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');

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

我得到的错误是: 1) 主要

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

2) 主要

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

UnhandledPromiseRejectionWarning: Error: blah UnhandledPromiseRejectionWarning: Unhandled promise rejection.

此错误是由于在没有 catch 块的情况下在异步函数内部抛出,或者是由于拒绝了未使用 .catch(). (rejection id: 228)

处理的承诺而引起的

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 中所述,检测类型并检测 async 函数作为 function

应该是:

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

async 函数是承诺的语法糖,它们不会抛出错误但 return 拒绝承诺。

应该是:

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