Visual Studio Code Mocha ProblemMatcher

Viewed 476
1 Answers

Seems like all built-in reporters describe the error with variable number of lines. And building vscode problem matcher for such kind of reporting is not supported - multiline support is extremely limited.

But we can build our own reporter with whatever format we like and then match on it with ease!

Here is a simple reporter which extends default Spec reporter with outputting errors with $tsc-watch matcher compatible format:

// my-reporter.js
var StackTraceParser = require('stacktrace-parser');
var path = require('path');
var mocha = require('mocha');
module.exports = MyReporter;

function MyReporter(runner) {
  mocha.reporters.Spec.call(this, runner);

  runner.on('fail', function(test, err){
    var lines = StackTraceParser.parse(err.stack)
    // we are only interested in the place in the test which originated the error
    var line = lines.find(line => line.file.startsWith('test'))
    if (line) {
      console.log(`${line.file}(${line.lineNumber},${line.column}): error TS0000: ${err.message.split('\n')[0]}`)
    }
  });

}

// To have this reporter "extend" a built-in reporter uncomment the     following line:
mocha.utils.inherits(MyReporter, mocha.reporters.Spec);

Add command to scripts section in package.json:

"test": "mocha --reporter my-reporter.js"

You then add to your tasks.json:

{
  "type": "npm",
  "script": "test",
  "problemMatcher": [
    {
      "applyTo": "allDocuments",
      "fileLocation": "relative",
      "base": "$tsc-watch",
      "source": "mocha"
    }
  ],
  "group": {
    "kind": "test",
    "isDefault": true
  }
}
Related