Search code examples
javascriptqunit

QUnit - equal vs assert.equal?


I know that it is possible to write something like this

QUnit.test( "hello test", function( assert ) {
  assert.ok( 1 == "1", "Passed!" );
});

as it is mentioned in QUnit documentation.

However, there is also a possibility to do that

QUnit.test( "hello test", function() {
  ok( 1 == "1", "Passed!" );
});

The problem for me in the second version is that this ok method is not resolved and I cannot go to the implementation, however, the problem what I see in the first case is that I need to pass this assert to the verificationMethod if I have one and this feels weird.

So, which way is better and why?


Solution

  • Back in the day we (the JS community) had no problem with defining a bunch of global functions (like ok() in your example). But as we've grown we've realized that this pollution of the global namespace (window) is a bad idea. That's what you have in the second example in your original post.

    When JavaScript can't find a variable (including functions) in the local scope, it begins to look outward along the scope chain. Eventually the JS engine will come to the window object - our global context in browser JavaScript. If the engine still doesn't find the variable then we get a ReferenceError. In your case, the ok function is created on the window object. You can confirm this by checking that window.ok === ok.

    But as I said, we, as a community, have moved away from global functions. A few years ago QUnit decided to provide a better interface for avoiding global functions and thus preventing potential naming collisions. This came in two forms: the QUnit global namespace and the assert argument into test callback functions. (We used to just write test(function() { ... }) without the QUnit namespace at all.)

    So... to answer your question... you should use the first form (assert.ok()) because it means you are not relying on the globally defined ok function to exist, which may actually collide with some other library. When QUnit executes your test functions it will provide that test function the assert argument which will point to the assertion library built into the QUnit framework. (Additionally, you will notice that all of the examples on the QUnit site use this form.)

    You can read more about this change in the documentation for the 2.x upgrade.