从堆栈跟踪中获取文件名

时间:2016-09-14 18:57:36

标签: javascript node.js unit-testing filenames

我有一个失败的单元测试,我正在写一个自定义的jasmine记者,要求我从它提供的堆栈跟踪中获取文件的名称。

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.....

从上面获取文件xyz.test.js的名称的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用正则表达式,但如果您想要更多功能,stacktrace-parser很有用:

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

答案 1 :(得分:0)

如果回溯存储在字符串中,并且您想使用正则表达式提取文件名(可能不适用于所有类型的例外):

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