【问题标题】:Chai Mocha test Promise Property 'eventually' does not existChai Mocha 测试 Promise Property '最终' 不存在
【发布时间】:2019-09-15 04:20:26
【问题描述】:

我正在尝试使用 Chai Promise 测试,但它显示错误 我正在使用 docker。

这里是一个简单的函数

            let funcPromise = (n) => {
                return new Promise((resolve, reject) =>{
                    if(n=="a") {
                        resolve("success");
                    }else {
                        reject("Fail")
                    }
                })
            }

简单测试

            import chai from 'chai';
            var chaiAsPromised = require('chai-as-promised');
            chai.use(chaiAsPromised);
            let expect = chai.expect;
            let assert = chai.assert;               

            it('connect: test promise', (done) => {
                let func = funcPromise("a");
                expect(func).to.eventually.equal("success"); // dont work
                expect(func).to.be.rejected; // dont work
            })

终端错误 FileTest.spec.ts:43:25 - error TS2339: Property 'eventually' does not exist on type 'Assertion'.

storage/database/MongooseEngine.spec.ts:44:35 - error TS2339: Property 'rejected' does not exist on type 'Assertion'.

【问题讨论】:

    标签: typescript unit-testing mocha.js chai


    【解决方案1】:

    错误是 TypeScript 抱怨它不知道 chai-as-promisedchai 断言所做的添加。

    添加 types for chai-as-promised 应该可以解决 TypeScript 错误:

    npm install --save-dev @types/chai-as-promised
    

    您还需要awaitchai-as-promised 所做的任何断言:

    import chai from 'chai';
    import chaiAsPromised from 'chai-as-promised';
    chai.use(chaiAsPromised);
    const expect = chai.expect;
    
    const funcPromise = (n) => new Promise((resolve, reject) => {
      if (n === 'a') { resolve('success'); }
      else { reject('fail'); }
    });
    
    it('connect: test promise', async () => {
      await expect(funcPromise('a')).to.eventually.equal('success');  // Success!
      await expect(funcPromise('b')).to.be.rejected;  // Success!
    });
    

    【讨论】:

    • 我能问你点什么吗?如果我像这样使用 done 和 done() it( ... (done) => { ...other code... done() }); 它会抛出 Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both. 如果我在最后省略 done() 它会抛出 Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise 你知道为什么吗?或者我可以在哪里读到它?
    • This section 是一个很好的资源。该错误意味着您正在使用 done 返回 Promise (通过直接返回 Promise 或使用 async 测试函数)。 Mocha 抛出该错误,让您知道不需要两者都做...选择使您的测试更容易的那个(我通常使用async 函数并在测试期间在任何Promises 上调用await)@滚动
    猜你喜欢
    • 2019-02-04
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 2014-12-21
    • 2016-06-11
    相关资源
    最近更新 更多