Is there a proper assert construct in Jasmine?

55 views
Skip to first unread message

Mihai Danila

unread,
Aug 24, 2016, 7:02:23 PM8/24/16
to Jasmine
As in:

function assert(condition, ...) {
  if (!condition)
    throw new AssertionException(...);
}

I've seen "expect"s being called "assert"s, but they are not the same thing. An assertion is a hard stop beyond which it doesn't make sense to execute code. For example, here's how I might check with assertions that there's exactly one image element on the page:

var imgs = document.getElementsByTagName('img');
assert(imgs.length).toBe(1);
expect(imgs[0].src).toBe(something);
...

And here's how we have to do it with expectations, in effect duplicating our test:

var imgs = document.getElementsByTagName('img');
expect(imgs.length).toBe(1);
if (imgs.length == 1) {
  expect(imgs[0].src).toBe(something);
  ...
}

Or else the test may fail miserably with an exception instead of a nice assertion:

var imgs = document.getElementsByTagName('img');
expect(imgs.length).toBe(1);
expect(imgs[0].src).toBe(something);  // If imgs was empty, ka-boom!
...

Gregg Van Hove

unread,
Sep 7, 2016, 7:18:34 PM9/7/16
to jasmi...@googlegroups.com
You can cause Jasmine's `expect` failures to behave how you want by setting the "Stop spec on expectation failure" configuration to true. The exact way to do this varies depending on whether you're using the ruby gem, npm package, etc. Under the covers this makes Jasmine `throw` an error to stop execution.

Hope this helps. Thanks for using Jasmine!

- Gregg

--
You received this message because you are subscribed to the Google Groups "Jasmine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jasmine-js+unsubscribe@googlegroups.com.
To post to this group, send email to jasmi...@googlegroups.com.
Visit this group at https://groups.google.com/group/jasmine-js.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages