搜索

首页  >  问答  >  正文

为什么我的 chai-as-promised 拒绝方法不能正常运行?

我使用摩卡、柴和承诺的柴。 测试应该失败,但没有,我不知道出了什么问题,有什么建议吗?

const { describe, it } = require('mocha')
const chai = require('chai')
const { expect } = require('chai')
const chaiAsPromised = require('chai-as-promised')

chai.use(chaiAsPromised)

describe('test', () => {
    it('must be rejected', async () => {
        expect(Promise.resolve('success')).to.rejected
    })
})

我试图测试一个应该被拒绝的承诺,测试应该失败,但测试成功了

P粉270891688P粉270891688229 天前378

全部回复(1)我来回复

  • P粉515066518

    P粉5150665182024-04-03 00:15:38

    摘自Chai as Promised 文档

    您可以使用 async /await.then(() => {}) 在测试中包含多个 Promise。

    这四个测试将失败:

    const { describe, it } = require('mocha');
    const chai = require('chai');
    const { expect } = require('chai');
    const chaiAsPromised = require('chai-as-promised');
    
    chai.use(chaiAsPromised);
    
    describe('test', () => {
      it('must be rejected (1)', () => {
        return expect(Promise.resolve('success')).to.eventually.be.rejected;
      });
    
      it('must be rejected (2)', (done) => {
        expect(Promise.resolve('success')).to.eventually.be.rejected.notify(done);
      });
    
      it('must be rejected (3)', async () => {
        await expect(Promise.resolve('success1')).to.eventually.be.fulfilled;
        return expect(Promise.resolve('success2')).to.eventually.be.rejected;
      });
    
      it('must be rejected (4)', () => {
        return expect(Promise.resolve('success1')).to.eventually.be.fulfilled.then(
          () => expect(Promise.resolve('success2')).to.eventually.be.rejected
        );
      });
    });
    

    实例:https://stackblitz.com/edit/node- a7t3tx?file=index.js

    回复
    0
  • 取消回复