Print message on expect() assert failure

jest expect with custom error message
jasmine expect to fail
jasmine withcontext
expect tothrow
jasmine tobetruthy
jest custom matchers

Is there a way to print a custom error message when a Jasmine expect() fails?

As an example, for end to end testing I have an array of web pages and I use one test to go to each URL and assert an element exists on each page. I know I can put every expect() into a separate test, but I'd rather iterate through the array and log the page URL on failure.


I see people still are finding this. Later information from the Jasmine team is that there is an undocumented feature on the expect - you can include a custom failure message and it just works:

expect( fields[i].element.exists() ).toEqual(true, field[i].name + ' is expected to exist');

Which is exactly what I was originally looking for.

Original answer follows:

I've been looking for exactly this today, and put a comment here:

The syntax that has been discussed is an extension to Jasmine to permit a because to be added - so you'd be able to write:

expect( fields[i].element.exists() ).toEqual(true).because( field[i].name + 'is expected to exist');

That is still being discussed after a few years, and may not come to fruition. Another way that I've found to do this is to create a custom matcher. In general I think I'd discourage a custom matcher without being sure you're covering all the bases with it, but in this case we're really checking a true/false value, so the matcher isn't too scary.

We can create the custom matcher with a beforeEach:

beforeEach(function() {
  var matchers = {
    toEqualBecause: function( value, message ) {
      this.message = function() {
        return "Expected '" + this.actual + "' to equal '" + value + "' because " + message;  

      return this.actual == value;  


We can then use this matcher to put a message with our failures as such:

expect( field[i].element.exists() ).toEqualBecause( true, field[i].name );

Which will give a failure output including the field name as such:

Expected 'false' to equal 'true' because account_name

Add explanation string to jasmine's expect() failure message · Issue , Add explanation string to jasmine's expect() failure message #2752. Closed. gruehle opened this issue on Jan 31, 2013 · 32 comments. Closed  When the matcher fails, and doesn't provide a custom message; Jasmine creates a default failure message based on all of the parameters passed to the expectation. This means that expect(1).toEqual(2, 'because of stuff') ends up printing out: Expected 1 to equal 2, 'because of stuff'. Presumably though, real code would look something more like:

Yes, we can print a custom error message when an expect() failed in Jasmine.

 Code Snippet:

  it('print a custom error message when an expect failed', function() {

    var elemenToBeDisplayed=element(by.css("userName"));

    /*custom error message will be displayed if expected condition 

    expect(elemenToBeDisplayed.isPresent).toBe(true,'Write your custom       
         error message here');

Custom error messages for assertions · Issue #3293 · facebook/jest , yarn add --dev jest echo 'it("works", () => { expect(true). I get that it's not possible to add a message as a last param for every assertion. Use assert instead of expect is the current workaround if you really need it @SimenB perhaps is obvious, but not for me: where does this suggested assert come from? I search for it in and it does not seem to be a jest api.

Jasmine 3.3 includes withContext as the officially supported way to specify additional information about the expectation without worrying about which matcher you are using.

customized message - RSpec Expectations - RSpec, RSpec tries to provide useful failure messages, but for cases in which you want 1 # trigger a failure to demonstrate the message expect(array).to be_empty,  If you pass a regular unawaited promise, TestCafe throws an error. If you need to assert a regular promise, set the allowUnawaitedPromise option to true. await t.expect(doSomethingAsync()).ok('check that a promise is returned', { allowUnawaitedPromise: true });

I had a requirement to log custom messages for Jasmine and I used the following method.

        customError: function(mesg){
                         this.message= function () {
                                           return mesg;
                         return this.actual == true;
if(<fail condidtion>){
    expect(false).customError(<Fail message>)

Please do note, what I have mentioned above is by jasmine 1 format. There will been slight change if you are using jasmine 2. Hope this is helpful for you

Bioinformatics Programming Using Python: Practical Programming for , It is better than just using assert for testing code because an assertion failure result): """Return expected == result, printing an error message if not true; use by​  Assertion introspection details¶. Reporting details about a failing assertion is achieved by rewriting assert statements before they are run. Rewritten assert statements put introspection information into the assertion failure message.

The other answers explain how to hack 'expect', but there is another approach that may solve your problem, though it requires you to flip your thinking around a little bit. Instead of thinking of the 'expect' as your behavior under test, think of all the expectations under a single 'it' call as your behavior under test.

The case where I've come across this problem the most is when I have a function that is doing some kind of intensive parsing and I want to write 20, nearly identical, tests.

Arrange your inputs and outputs like so:

var testDatas = [
    input: 'stringtoparse1',
    output: 'String To Parse 1'
    input: 'stringtoparse2',
    output: 'String To Parse 2'
    input: 'stringtoparse3',
    output: 'String To Parse 3'

Now iterate over the list of your test data, and call 'it' from inside the loop like so:

testDatas.forEach(function(test) {
  it('should parse for input ' + test.input, function() {

You get to reduce the amount of extraneous code flying around your tests and you get to format a message for each expectation, or group of expectations.

Beginning Java 8 Fundamentals: Language Syntax, Arrays, Data , Note that the errorMessageExpression in the second form of assert statement Did you not expect an error message on the standard output? the error message also contains your custom assertion message, which prints the value of x. CPPUNIT_ASSERT_EQUAL_MESSAGE("message",EXPECTED_VALUE,ACTUAL_VALUE) And allows to send custom messages to test output. Is there a way to include some custom text in google test output? (Preferably the way that could include message to data that is read by existing programs for automated unit testing using google test.)

Writing tests, Assert the results are what you expect. The function body uses the assert_eq! macro to assert that 2 + 2 equals 4. 2 + 2, 4); } #[test] fn another() { panic! The it_adds_two test failed, displaying the message assertion failed: `(left == right)` and When the assertions fail, these macros print their arguments using debug  Python Assert Statement In this article we will learn about assertion in Python using assert.

Encyclopedia of Software Engineering Three-Volume Set (Print), Assert function Description assertEquals([String message], expected, actual [​tolerance]) Causes the unit test to fail if expected is not equal to actual. If tolerance  This will print something like this: expect failure message to make sure users of your custom assertions have a good developer experience. into the expect

Set error message - Help, expect along with .equal which accepts a second argument with custom message​. For example: pm.test('Status code', function() { pm.expect  Information about the assertion failure, specified as a character vector or string scalar. This message displays as the error message. To format the message, use escape sequences, such as \t or . You also can use any format specifiers supported by the sprintf function, such as %s or %d.

  • awesome find! expect(something).toBeFalsy('should not...'); works too
  • Hi! Surely you should place your latest discovery on top of your answer, so it's directly accessible (leave the rest as historic logs below). Thx.
  • As of jasmine 3.3.0 it seems to work with toBe, but not with toEqual
  • Still not working with toEqual, despite it is documented. With toBe you test exactly the same values which fails on objects (maybe because the prototype part) so still inapplicable :(
  • I think it is ridiculous this is 'still being discussed'. This is an obvious feature of test frameworks and has been since their inception. Thanks for showing the workaround.
  • While this syntax currently works, it is not documented and should be used with care.
  • Nice. The same trick doesn't seem to work for toEqual. Any work-around there?
  • @ Suresh Salloju it doesn't =\
  • @StavAlfi what?
  • Hey, @HolgerJeromin, I'm using jasmine 3.3.1, I write expect(true).withContext("reason").toBe(false); and I get Failed: expect(...).withContext is not a function. Any ideas why it is happening?
  • @SergeyPleshakov I use Jasmine 3.3.0 with the expected result: reason: Expected true to be false.
  • Wow, I wondered how a test runner would count the number of tests with something like this and found that with a for loop (using Chutzpah test runner and Jasmine in Visual Studio) that it added all iterations as individual tests to the Test Explorer!
  • Hey, @ernstjan, I'm using jasmine 3.3.1, I write expect(true).withContext("reason").toBe(false); and I get Failed: expect(...).withContext is not a function. Any ideas why it is happening?