Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code after Jasmine test failure

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.

like image 854
The DIMM Reaper Avatar asked Jul 13 '15 17:07

The DIMM Reaper


People also ask

What is beforeEach in Jasmine?

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.

What is test suite in Jasmine?

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.

Which files are required for Jasmine in HTML?

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.


1 Answers

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;
    }
});
like image 74
tlrobinson Avatar answered Sep 28 '22 01:09

tlrobinson