Running tests on Typescript source code Versus the generated JavaScript

Viewed 726

In a web project where TypeScript is used to program the entire application, front-end and back-end, and as well as tests. Then it is all compiled and deployed as JavaScript;

What is desirable to run the tests on during deployment. Does it make more sense to run it on the TypeScript source code directly? Or does it make more sense to run it on the resulting generated JavaScript (which is later deployed to server)

Remember that depending on which it is run on, it has some minor implications on things like code-coverage reporting for example.

One school of thought is to run it on the TypeScript source code, because that is what the programmer is producing and has direct control over.

On the other hand, it is the JavaScript generated code that ultimately runs after it has been deployed.

Is there an accepted pattern to this?

1 Answers

I used to test its js compiled code, but then I found that running the test over the Typescript files more makes sense. The main strong reason is for easier debugging if any test is failed because we code and test on the same Typescript file.

Below is an example for debugging a failed test:

⚠️ See the expect line number which has a discrepancy in Typescript and compiled Javascript

test.ts

import { expect } from 'chai';

describe('sum', () => {
  it('should return 3', () => {
    expect(2 + 1).to.equal(2); // line 5
  })
})

and its js compiled

"use strict";
exports.__esModule = true;
var chai_1 = require("chai");
describe('a', function () {
    it('should return a', function () {
        chai_1.expect(2 + 1).to.equal(2); // line 6, different number to its source code
    });
});

Test result over the Typescript file using ts-mocha shows the correct problematic line number for line 5

sum
    1) should return 3


  0 passing (12ms)
  1 failing

  1) sum
       should return 3:

      AssertionError: expected 3 to equal 2
      + expected - actual

      -3
      +2
      
      at Context.<anonymous> (mocha/65152263/a.test.ts:5:22) <--- Match with Typescript source code ✅
      at processImmediate (internal/timers.js:439:21)

Meanwhile, for the js test result, it will give you line number 6.

For a small test file, it might be not too cumbersome to find the issue, but not great if we have many tests.

Related