简体   繁体   中英

get filename from a stacktrace

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?

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).*\)

正则表达式可视化

Debuggex Demo

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM