Why Would I ever use expect() When Writing Tests With QUnit?
Asked Answered
B

2

10

I've recently started using QUnit to unit test my JavaScript and I'm a little confused by a feature in there documentation: expect().

According to the docs, expect() is designed to:

[s]pecify how many assertions are expected to run within a test.

And here's the example they give:

test( "a test", function() {
  expect( 2 );

  function calc( x, operation ) {
    return operation( x );
  }

  var result = calc( 2, function( x ) {
    ok( true, "calc() calls operation function" );
    return x * x;
  });

  equal( result, 4, "2 square equals 4" );
});

The only thing I see here is maintenance nightmare. Every time you add an assertion to a test, you have to update that number or the test will fail. Is there a practical application for this kind of feature?

Brooklynese answered 21/2, 2013 at 1:38 Comment(2)
Complete guess from someone who knows bugger all about QUnit: It can be used as a guard against infinite loops. It seems to impose a maximum limit, not a minimum, so you can use expect(100) (or similar) and it should be fine.Ipomoea
This is wrong, it's neither a minimum or a maximum, it defines the exact amount of assertions that you expect. If the number is below or above the excpetation, the test will fail.Chickabiddy
A
10

The only thing I see here is maintenance nightmare... Is there a practical application for this kind of feature?

Well, the way I think expect is meant to be used is with grouped meaningful tasks. It's useful for testing events or callbacks, for example:

test('trigger an event', function() {
  expect(1);

  $('div')
    .on('click', function() { ok(1) });
    .trigger('click');
});

It doesn't become a nightmare if you keep meaningful tasks grouped in small tests, where only 2 or 3 assertions are expected.

Agram answered 21/2, 2013 at 1:52 Comment(1)
To elaborate a bit, when you're testing asynchronous code, there's a chance the async event won't happen and your test won't run. In that case, you'd want a failure, not a silently skipped test.Natalia
B
3

It can be used as a safeguard to ensure that you haven't somehow written a test that can't be run. If you get into the habit of writing the expected number of tests, should you ever somehow write a test suite where one test is hidden from QUnit for some reason, QUnit will pick this up before you would.

Bringhurst answered 11/3, 2014 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.