Is it possible to do something only if a Jasmine test fails? Juxtaposed with afterEach()
which executes after an it()
regardless of outcome, I'm looking for some way to execute code only after an it()
has a failed expectation.
This question is not Angular-specific, but in my scenario I am testing an Angular service which outputs debug messages using $log
. I don't want to clutter my console for tests that are successful, but only show the additional information for failing tests.
describe("MyService", function() {
var MyService, $log;
beforeEach(function() {
inject(function (_MyService_, _$log_) {
MyService = _MyService_;
$log = _$log_;
});
});
afterEach(function () {
if (/* test failed */) {
//console.log($log.debug.logs);
}
});
it("should output debug logs when this fails", function() {
//do something with MyService that would put a message in $log
expect(false).toBe(true);
});
});
I'm running Jasmine 2.2.0.
Edit: here's a very simple fiddle which shows the Jasmine 1.3 jasmine.getEnv().currentSpec
solution no longer working.
JasmineJS - beforeEach() Advertisements. Another notable feature of Jasmine is before and after each function. Using these two functionalities, we can execute some pieces of code before and after execution of each spec. This functionality is very useful for running the common code in the application.
In terms of Jasmine, a test consists of one or more suites. A suite is declared with a describe block: describe('Suite description', () => { /* … */ }); Each suite describes a piece of code, the code under test.
The standalone Jasmine framework comes with a file called SpecRunner. html , which is simply the HTML file that puts all your source and spec files together, runs them in a browser using that browser's JavaScript engine, and returns a page that shows you how many/which of your tests passed and failed.
Here's a hack to re-enable jasmine.getEnv().currentSpec
in Jasmine 2 (sort of, result
isn't the full spec
object, but contains id
, description
, fullName
, failedExpectations
, and passedExpectations
):
jasmine.getEnv().addReporter({
specStarted(result) {
jasmine.getEnv().currentSpec = result;
},
specDone() {
jasmine.getEnv().currentSpec = null;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With