2

所以我试图测试我的异步函数在我存根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 应该是一个函数: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:错误:等等 UnhandledPromiseRejectionWarning:未处理的承诺拒绝。

此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未处理的承诺.catch(). (rejection id: 228)

4

1 回答 1

1

正如在这个答案中所解释的,一个函数是否存在并不重要async,只要它返回一个承诺。Chai 依赖于type-detect检测类型和检测async函数为function.

它应该是:

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

async函数是 Promise 的语法糖,它们不会抛出错误,而是返回被拒绝的 Promise。

它应该是:

getS3File().should.be.rejectedWith(Error); 
于 2018-09-14T13:31:43.640 回答