power-assert-js / espower-typescript

power-assert instrumentor for TypeScript
https://npm.im/espower-typescript
86 stars 11 forks source link

Error stacks line number is not correct #54

Closed whxaxes closed 6 years ago

whxaxes commented 6 years ago

Hi, I found the line number of error stacks is not correct in my project.

image

As you see, the line number should be 5 and 10, but result is

image

The line number is 30 and 35.

You can try in this repo : https://github.com/whxaxes/espower-typescript-stacks-demo

$ npm install
$ npm run test
whxaxes commented 6 years ago

I just fix this bug by overwrite sourceMapSupport.retrieveFile

// fix-source-map.js

const path = require('path');
const sourceMapSupport = require('source-map-support');
const cacheMap = {};
const extensions = ['.ts', '.tsx'];

sourceMapSupport.install({
  environment: 'node',
  retrieveFile: function (path) {
    return cacheMap[path];
  }
});

extensions.forEach(ext => {
  const originalExtension = require.extensions[ext];
  require.extensions[ext] = (module, filePath) => {
    const originalCompile = module._compile;
    module._compile = function(code, filePath) {
      cacheMap[filePath] = code;
      return originalCompile.call(this, code, filePath);
    };
    return originalExtension(module, filePath);
  };
})

and require this code after espower-typescript/guess

--require espower-typescript/guess
--require ./fix-source-map.js
--recursive
test/**/*.test.ts

it works !!!

image

Now the line number and column number is correct as expected.

the reason is that ts-node cache the code in https://github.com/TypeStrong/ts-node/blob/master/src/index.ts#L218

    // Install source map support and read from memory cache.
    sourceMapSupport.install({
        environment: 'node',
        retrieveFile: function (path) {
            return memoryCache.outputs[path];
        }
    });

so the source-map-support use wrong sourceMap to map the code.

teppeis commented 6 years ago

@whxaxes thanks!