【问题标题】:Assertion error when testing async function with mocha and chaiAsPromised使用 mocha 和 chaiAsPromised 测试异步函数时的断言错误
【发布时间】:2019-02-19 05:17:06
【问题描述】:

所以我试图测试我的异步函数在我存根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: 预期 [Function: getS3File] 是一个异步函数 在 Context.it (test\unit\main.spec.js:28:27)

2) 主要

getFileFromS3 有错误 应该与blah错误:AssertionError:预期[Function:getS3File]抛出错误

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

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

【问题讨论】:

  • getS3File = sut.__get__('getS3File'); .我认为这条线引起了问题。您将异步函数引用更改为其他值。将 getS3File 变量名称更改为其他名称并尝试

标签: javascript node.js mocha.js chai chai-as-promised


【解决方案1】:

正如this answer 中所解释的,函数是否为async 并不重要,只要它返回一个promise。 Chai 依赖type-detect 检测类型,检测async 函数为function

应该是:

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

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

应该是:

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

【讨论】:

    猜你喜欢
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 2014-02-08
    • 2020-02-26
    • 2015-10-23
    • 2015-03-26
    相关资源
    最近更新 更多