Instead of a bug, the TypeScript compiler is doing its job but causing my Travis builds to fail.
In my package, I have a function named completeRound
which accepts a number as its first argument and 3 optional arguments. Since it's in TypeScript, I specify that it requires a number as the first argument:
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!');
}
// Additional code here
}
While everything operates fine, testing poses an issue. In my testing script:
import completeRound from '../src/completeRound';
import { expect } from 'chai';
import 'mocha';
const expectedResults = [
{
testVal : {
number : 3.5,
rounding : 1,
direction : 'down'
},
eR : 3
},
// Numerous other tests, all passing correctly
];
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);
});
}));
/* This line presents the problem */
expect(() => completeRound([5])).to.throw(TypeError, /a number/);
/* ---------------------------- */
expect(() => completeRound(5,1,'arriba')).to.throw(Error, /valid rounding direction/);
The challenge arises when I pass an array instead of a number, expecting JavaScript to trigger a TypeError. It's crucial for users utilizing either JavaScript or TypeScript to be equally covered. Furthermore, aiming for a flawless 100% coverage report. Nevertheless, the Travis report below reveals that the TypeScript compiler identifies the error first and throws a compilation error.
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/);
I'm unable to test the compiled code directly, as it necessitates compiling it through webpack, storing it in the ./dist
directory, and bundling it, complicating the process. Importing from this output seems impractical, and having a two-step process involving compiling then bundling isn't ideal.
In essence, I seek to ascertain JavaScript's ability to catch errors that TypeScript would detect automatically but JavaScript wouldn't. Any assistance would be greatly appreciated.