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?
Note expect and should uses chainable language to construct assertions, but they differ in the way an assertion is initially constructed. In the case of should , there are also some caveats and additional tools to overcome the caveats. var expect = require('chai').
Create a Test CaseMake a call to the QUnit. test function, with two arguments. Name − The name of the test to display the test results. Function − Function testing code, having one or more assertions.
describe() allows you to gather your tests into separate groupings within the same file, even multiple nested levels. Now, nesting is one of the most-maligned features of RSpec, because it's easy to take it too far.
Both the describe and it functions accept two parameters: a descriptive string and a callback function. Though the functions are flexible, they are commonly used in the structure above: nest describe blocks to resemble the structure of your implementation code and write individual tests in it blocks.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With