From 7caebddcb281d51450e761bf85869e552d960aba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pierre-Yves=20G=C3=A9rardy?= Date: Thu, 30 Nov 2017 01:36:47 +0100 Subject: [PATCH] ospec: better stack trace filter, fix #2036 --- ospec/README.md | 2 +- ospec/ospec.js | 24 ++++++++++++++++-------- ospec/tests/test-ospec.js | 2 +- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/ospec/README.md b/ospec/README.md index 7a257b31..b3a3ff76 100644 --- a/ospec/README.md +++ b/ospec/README.md @@ -490,7 +490,7 @@ True if the test passed. **No other keys will exist on the result if this value ### Error result.error -The value of the stack property from the `Error` object explaining the reason behind a failure. +The `Error` object explaining the reason behind a failure. --- diff --git a/ospec/ospec.js b/ospec/ospec.js index 29f7fdef..1c7cb94c 100644 --- a/ospec/ospec.js +++ b/ospec/ospec.js @@ -9,11 +9,7 @@ else window.o = m() if (name != null) spec[name] = ctx = {} try {throw new Error} catch (e) { - var stackTraceMatcher = new RegExp( - "^(?:(?!Error|" - + e.stack.match(/[\/\\](.*?):\d+:\d+/)[1] - + ").)*$", "gm" - ) + var ospecFileName = e.stack.match(/[\/\\](.*?):\d+:\d+/)[1] } function o(subject, predicate) { if (predicate === undefined) { @@ -58,8 +54,19 @@ else window.o = m() spy.callCount = 0 return spy } - o.cleanStackTrace = function(stack) { - return stack.match(stackTraceMatcher).pop() + o.cleanStackTrace = function(error) { + var i = 0, header = error.message ? error.name + ": " + error.message : error.name, stack + // some environments add the name and message to the stack trace + if (error.stack.indexOf(header) === 0) { + stack = error.stack.slice(header.length).split(/\r?\n/) + stack.shift() // drop the initial empty string + } else { + stack = error.stack.split(/\r?\n/) + } + // skip ospec-related entries on the stack + while (stack[i].indexOf(ospecFileName) !== -1) i++ + // now we're in user code + return stack[i] } o.run = function(_reporter) { results = [] @@ -230,7 +237,8 @@ else window.o = m() } result.context = subjects.join(" > ") result.message = message - result.error = error.stack + result.error = error + } results.push(result) } diff --git a/ospec/tests/test-ospec.js b/ospec/tests/test-ospec.js index e837049d..86218c83 100644 --- a/ospec/tests/test-ospec.js +++ b/ospec/tests/test-ospec.js @@ -188,7 +188,7 @@ o.spec("ospec", function() { try { throw new Error("line\nbreak") } catch(error) { - var trace = o.cleanStackTrace(error.stack) + var trace = o.cleanStackTrace(error) o(trace).notEquals("break") o(trace.includes("test-ospec.js")).equals(true) }