2016-09-14 169 views
-1

我有一個失敗的單元測試,我正在寫一個自定義茉莉花記者,這將需要我從它提供的堆棧跟蹤中獲取文件的名稱。從堆棧跟蹤獲取文件名

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名的最好方法?

+0

的可能重複[我怎樣才能得到一個Javascript堆棧跟蹤,當我拋出一個異常?( http://stackoverflow.com/questions/591857/how-can-i-get-a-javascript-stack-trace-when-i-throw-an-exception) –

回答

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

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