Search code examples
javascriptjasmine

Can I get a return value from an expect() statement in Jasmine?


I have some test automation code written in Jasmine to test a web app. It has many statements of the form: expect(a).toBe(b) or expect(a).toEqual(b).

I am now working on updating my code to store results in a database. I have been given the direction that we don't care about storing results for tests which passed, and to only store failures.

My first attempt at this involves constructions like the following:

expect(a).toBe(b);
let result = (a == b) ? "pass" : "fail";
if(result == "fail") {
 // write to database
}

However, there are some cases in which a and b are objects or arrays, rather than primitive types. In this case, I think I can use expect(a).toEqual(b) to do a deep comparison, but I can't use the comparison of a == b to decide whether this is a failure that should be in the database.

Is there a way for me to get a return value from the expect() statement, or otherwise inspect whether the test passed or failed? This would both save me the trouble of writing my own comparator for a and b, and ensure that I am writing to the database only on a test case failure.


Solution

  • Could you implement your own Custom Reporter?

    Building off the example above, you could override the specDone function to log to a database or anything else.

    const myReporter = {
      specDone: function(result) {
        console.log('Spec: ' + result.description + ' was ' + result.status);
    
        for (const expectation of result.failedExpectations) {
          // log to database
        }
      },
    
    };
    

    Register the reporter with jasmine

    jasmine.getEnv().addReporter(myReporter);