繁体   English   中英

使用 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 应该是一个函数:AssertionError: expected [Function: getS3File] to be an asyncfunction at Context.it (test\\unit\\main.spec.js:28:27)

2) 主要

带有错误的 getFileFromS3 应该出错:AssertionError: expected [Function: getS3File] to throw an error

UnhandledPromiseRejectionWarning:错误:等等 UnhandledPromiseRejectionWarning:未处理的承诺拒绝。

这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用.catch(). (rejection id: 228)处理过的承诺.catch(). (rejection id: 228) .catch(). (rejection id: 228)

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

它应该是:

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

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

它应该是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM