Travis CI构建过程-TypeScript在Mocha之前捕获错误

问题描述 投票:0回答:1

这不是TypeScript编译器完成其工作时的错误,但是它导致Travis构建失败。

在我的程序包中,我有一个函数completeRound,该函数将数字作为第一个参数,然后是3个可选参数,并且因为我已经在TypeScript中编写了它,所以我告诉它需要将数字作为第一个参数传入参数:

function completeRound( number: number, rounding = 1, direction = 'closest', offset = 0 ): number {
  let n: number = +number,
      r: number = Math.abs(+rounding),
      d: string = direction,
      o: number = +offset;

  if (typeof n !== 'number') {
    throw new TypeError('You need to round a number!');
  }

  // Rest of the code goes here
}

一切正常,唯一的麻烦就是测试。在我的测试脚本中,我有:

import completeRound from '../src/completeRound';
import { expect } from 'chai';
import 'mocha';

const expectedResults = [
  {
    testVal : {
      number    : 3.5,
      rounding  : 1,
      direction : 'down'
    },
    eR      : 3
  },
  // 40-something different tests, all passing fine
];

expectedResults.map(t => describe(`completeRound(${t.testVal.number}, ${t.testVal.rounding}, '${t.testVal.direction}', ${t.testVal.offset})`,() => {
  it(`should return ${t.eR}`, () => {
    const result = completeRound(t.testVal.number,t.testVal.rounding,t.testVal.direction,t.testVal.offset);
    expect(result).to.equal(t.eR);
  });
})); // For testing results where it shouldn't throw an error

/* This one is the problem line */
expect(() => completeRound([5])).to.throw(TypeError, /a number/);
/* ---------------------------- */

expect(() => completeRound(5,1,'arriba')).to.throw(Error, /valid rounding direction/);

因此,我要向它传递一个数组而不是一个数字,我想让JavaScript在其中抛出TypeError。显然,我希望人们能同样涵盖使用JavaScript或TypeScript的人。另外,我在覆盖率报告中追求100%的可观数字。 BUT,从Travis的以下报告中,我们可以看到TypeScript编译器首先到达那里并引发编译错误。

TSError: ⨯ Unable to compile TypeScript:

dev/test/completeRound.spec.ts:414:28 - error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'number'.

414 expect(() => completeRound([5])).to.throw(TypeError, /a number/);

我没有一种测试编译后的代码的方法,因为这意味着编译它,我正在使用webpack对其进行编译,然后将其直接放在./dist文件夹中,并对其进行浏览器化,所以我看不到如何从中导入,并且我真的不想要一个两步过程来编译它然后将其捆绑。

我想是简短的版本,我想测试JavaScript错误抛出是否有TypeScript会自动捕获它的错误,但JavaScript不会。

有人可以帮忙吗?

typescript testing npm mocha travis-ci
1个回答
0
投票

我看到至少两个问题:

  1. 在completeRound()函数上,您正在使用unary plus(n = + number),这意味着n始终具有类型编号(AFAIK)。您需要首先检查“数字”(第一个功能参数)。或者,如果以后仍要检查,可以使用isNaN()进行检查。示例(简化版):
function completeRound(number: number): number|TypeError {
  // Check the type of the first argument.
  if (typeof number !== 'number') {
    throw new TypeError('You need to round a number!');
  }
  // Before assign it.
  const n: number = +number;
  // For example if first parameter is function.
  if (isNaN(n)) {
    throw new TypeError('You need to round a number!');
  }
  // Rest of the code goes here
  return n;
}
  1. 您可以定义unknown,然后执行type assertion。例如:
const testVar:unknown = [5];
expect(() => completeRound(testVar as number)).to.throw(TypeError, /a number/);

希望这会有所帮助。祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.