DEV Community

Cover image for toBe(Void 0) In A Unit Test
bob.ts
bob.ts

Posted on

toBe(Void 0) In A Unit Test

I saw the following pattern in a clients Unit Tests. While the pattern seemed odd, I didn't immediately look into what the pattern meant; the tests were working correctly.

function toTestUndefined(state) {
  if (state === false) {
    return undefined;
  }
  return true;
}

it('testing void 0 pattern', function() {
  expect(toTestUndefined(false).toBe(void 0);
});
Enter fullscreen mode Exit fullscreen mode

The oddity that I found was the use of the void 0. This small set of code led me on a merry chase to determine what it was doing and why it was used as seen here.

Usage

The void operator evaluates the given expression and then returns undefined.

The void operator is often used merely to obtain the undefined primitive value, usually using void(0) (which is equivalent to void 0). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

This pattern is often used with an anchor tag.

<a href="javascript:void(0)" id="loginlink">login</a>
Enter fullscreen mode Exit fullscreen mode

JavaScript within a URL will redirect the browser to a plain text version of the result of evaluating the JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.

Within Jasmine

In this particular case, when I got with the developer who wrote the code he explained that the linter settings were different for tests than for the code under test. The linter for tests "complained" about the use of undefined and void 0 bypassed the complaint.

Summary

I recommended using it within a variable for clarity, resulting in something like the following ...

var _undefined = void 0;

it('testing void 0 pattern', function() {
  expect(toTestUndefined(false).toBe(_undefined);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)