简体   繁体   English

如何在 Typescript 中使用 chai-as-promised?

[英]How to use chai-as-promised with Typescript?

I'm trying to use chai-as-promised package with TypeScript.我正在尝试将chai-as-promised包与 TypeScript 一起使用。 First of all, the following code works well in simple JavaScript.首先,以下代码在简单的 JavaScript 中运行良好。

import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);
const expect = chai.expect;

import * as sinon from 'sinon';

import { MyClass } from '.';

describe('Test my class', () => {
  let myClass: MyClass;

  beforeEach(() => {
    myClass = new MyClass();
   });

  it('Should render home', () => {
    const req = new RequestMock();
    const res = new ResponseMock();

    return expect(myClass.getHomePage(req, res)).to.be.fulfilled()
      .then((returnedValue) => {
        chai.expect(returnedValue).to.not.be.equal([]);
      });
  });
});

I have the following error with this code :这段代码出现以下错误:

在此处输入图片描述

... and it pointed to this : ...它指出了这一点:

interface PromisedTypeComparison {
    (type: string, message?: string): PromisedAssertion; // <<-- 
    instanceof: PromisedInstanceOf;
    instanceOf: PromisedInstanceOf;
}

I tested plenty of opportunity and it is the one where I am closest to the solution it seems to me.我测试了很多机会,这是我最接近我认为的解决方案的机会。

I would like to use function of chai-as-promise like fullfulled , rejected ... etc.我想使用chai-as-promise功能,如fullfulledrejected ... 等。

How can i make it ?我怎样才能做到?

Just import the default of chai-as-promised and everything will work:只需导入chai-as-promised的默认值,一切都会正常工作:

import * as chai from 'chai'    
import chaiAsPromised from 'chai-as-promised'
chai.use(chaiAsPromised)

I think this answer is what you need:我认为这个答案正是你所需要的:

Add the types for chai-as-promised and that should take care of the TypeScript errors:添加chai-as-promised类型,这应该处理 TypeScript 错误:

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

Worked for me.为我工作。 Before, I was getting "Property 'eventually' does not exist on type 'Assertion'.";之前,我收到“‘断言’类型上不存在‘最终’属性。”; after adding this everyone was happy :-)添加此后,每个人都很高兴:-)

I did have to change my import to a require .确实必须将import更改为require

Before:前:

import chaiAsPromised from 'chai-as-promised';

After:后:

import chaiAsPromised = require('chai-as-promised');

You can write this way你可以这样写

import { use as chaiUse } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';

chaiUse(chaiAsPromised);

I think you are missing the '.eventually' or '.become' in the assertion.我认为您在断言中缺少“.eventually”或“.become”。 Try rewriting it as尝试将其重写为

expect(myClass.getHomePage(req, res)).to.eventually.be.fulfilled;

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

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