DEV Community

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

Posted on

3

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay