柴摩卡测试“最终”承诺财产不存在

时间:2019-04-25 16:57:24

标签: typescript unit-testing mocha chai

我正在尝试使用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'.

1 个答案:

答案 0 :(得分: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!
});