0

I have a failing unit test and i am writing a custom jasmine reporter that would requires me to get the name of the file from the stack trace provided by it.

Verify the most recent consumer review is showing all information. (0.683 sec) - Expected true to be false, 'test title'. at Object.<anonymous> (/Users/xyz/Documents/tests/somefolder/xyz.test.js:25:72) at /Users/xyz/Documents/node_modules/jasminewd2/index.js:96:23 at new Promise (/Users/xyz/Documentsc/node_modules/selenium-webdriver/lib/promise.js:1043:7.....

What is the best way just to get the name of the file xyz.test.js from above?

pj013
  • 1,393
  • 1
  • 10
  • 28
  • Possible duplicate of [How can I get a Javascript stack trace when I throw an exception?](http://stackoverflow.com/questions/591857/how-can-i-get-a-javascript-stack-trace-when-i-throw-an-exception) – Daniel Lizik Sep 14 '16 at 19:09

2 Answers2

1

If the traceback is stored in a string, and you want to extract the filename using regex (may not work for all types of exceptions):

var traceback = "Verify the most recent consumer review is showing all information. (0.683 sec) \
        - Expected true to be false, 'test title'. \
            at Object.<anonymous> (/Users/xyz/Documents/tests/somefolder/xyz.test.js:25:72) \
            at /Users/xyz/Documents/node_modules/jasminewd2/index.js:96:23 \
            at new Promise (/Users/xyz/Documentsc/node_modules/selenium-webdriver/lib/promise.js:1043:7....."
            
console.log(/\(.*\/([^\/]*.js).*\)/.exec(traceback)[1])
\(.*/([^/]*.js).*\)

Regular expression visualization

Debuggex Demo

Nehal J Wani
  • 16,071
  • 3
  • 64
  • 89
1

You could probably use a regexp for this, but if you want a bit more functionality, stacktrace-parser is useful:

const parse = require('stacktrace-parser').parse;
const path  = require('path');

let trace = `
        - Expected true to be false, 'test title'.
            at Object.<anonymous> (/Users/xyz/Documents/tests/somefolder/xyz.test.js:25:72)
            at /Users/xyz/Documents/node_modules/jasminewd2/index.js:96:23
            at new Promise (/Users/xyz/Documentsc/node_modules/selenium-webdriver/lib/promise.js:1043:7
`;

console.log( path.basename( parse(trace)[0].file ) )
// outputs: xyz.test.js
robertklep
  • 198,204
  • 35
  • 394
  • 381