简体   繁体   中英

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

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM