Yoda Expectations

| Tags: dart, dev, web

Since releasing the Dart testing framework dahlia two months ago, I have been using it on a Dart project of mine. Although I’m pretty satisfied with it, there’s one aspect of it that is somewhat ugly. To test something in dahlia you specify an expectation and look whether it holds as in

expect(a).to(equal(b))

For my taste there are too many parentheses there and normally you get an additional pair around it when you put it into a one-line it-block like in

it('a should equal b', ()
  => expect(a).to(equal(b)));

So I want to get rid of some of those parentheses and working on my project I took inspiration from Dart’s event system which provides a nice approach for defining event handlers. Here’s an example

someElement.on.click.add(....)

Now I’m experimenting with a new form of expectations

expect(a).to.equal(b)

That looks better. But what about negations and combinations?

expect(a).to.not.equal(b)

can be implemented quite easily, but

expect(a).to.equal(b).or.equal(c)

is another matter. There is no way to know that after the first equal-matcher an and-matcher and another equal-matcher follows as there is no finishing method call that completes the expectation. A solution is to find some expression that puts a marker at the start like

expect(a).to.either.equal(b).or.equal(c)

but “either a or b” is definitely not the same as “a or b” and isn’t really flexible.

Doing it Yoda-style seems to solve the problem

to.equal(b).or.equal(c).expect(a)

For the fun of it, you can make it sound even more like Yoda

to.equal(b).or.equal(c).expect(a).hmm()

I’m unsure whether it solves a real problem, though. Tests shouldn’t be that complicated that the need for combinations of matchers arises. And though it’s fun, the original form where you know the subject before what is expected of it is more readable.