摩卡咖啡:如何在打字稿中使用assert.reject并在参数中使用promise?

时间:2019-05-10 20:37:56

标签: node.js typescript mocha es6-promise chai

我该如何在typescript中使用assert.reject并在参数中使用promise?

这是我的代码:

import { assert } from "chai";
import { suite, test, timeout, slow } from "mocha-typescript";
import "mocha";
import { car } from "./Car"; // module that run your function

let carVIN: string = "1234567890"; // this car has four wheel;

@suit
export class CarTest() {
  @test
  public async oneWheelsCar() {
      const wheels = await car.findWheelsByCarId(carVIN);
      assert.isRejected(wheels, "Expected to have four wheels");
  }

}

我的问题是我如何使我的carId函数像promise一样运行,因为我的问题是assert.isRejected在carId错误返回之前提早运行。

我在下面尝试过:

assert.throws(carId, Error, "Expected to be error ");

并且我还尝试使用try-catch包装我的函数:

import { assert } from "chai";
import { suite, test, timeout, slow } from "mocha-typescript";
import "mocha";
import { car } from "./Car"; // module that run your function

let carVIN: string = "1234567890"; // this car has four wheel;

@suit
export class CarTest() {
  @test
  public async oneWheelsCar() {
      try {
        const wheels = await car.findWheelsByCarId(carVIN);
        assert.isNotString(wheels, "Expected to be error but return four wheels");
      } catch (error) {
        assert.throws(error, Error, "Expected to be error ");
      }

    }

}

我曾尝试使用chai-as-promise,但是在他们的github存储库中,该示例并不清楚。

访问https://github.com/domenic/chai-as-promised#readme

来源:https://www.npmjs.com/package/chai-as-promised

1 个答案:

答案 0 :(得分:0)

问题是awaitawait将承诺解析为实际值或引发异常(简化视图)。

因此,在这一行之后:

const wheels = await car.findWheelsByCarId(carVIN);

wheels不是承诺,而是实际的wheel(或其他)。

将其更改为:

const wheelsPromise = car.findWheelsByCarId(carVIN); // no await

然后这个:

assert.isRejected(wheelsPromise, "Expected to have four wheels");

应能按预期工作。