How to Unit-test A Private (non-exported) Function in JavaScript

How to Unit-test A Private (non-exported) Function in JavaScript

Originally published at https://www.wisdomgeek.com on November 19, 2020.

Originally published at https://www.wisdomgeek.com on November 19, 2020.

When writing unit-tests for JavaScript modules, we often encounter a dilemma wherein the module has some private functions that have not been exported. Testing a function that has been exported is easy since it can be imported in the unit testing framework, and the functionality can be tested. But how to unit-test a private (non-exported) function?

Testing exported function

Before we get to the private functions, let us get familiar with how we would test an exported function in JavaScript. We will be using Jest for writing this unit test. Let us assume a function foo such that:

// foo.js
export function foo() {
  return 'bar';
}

We will then write the corresponding unit test case for testing the functionality of the exported function as:

// foo.test.js
import { foo } from './foo.js'

describe('testing foo', () => {
  expect(foo()).toBe('bar');
});

Now that we are familiar with exported functions let us move to the next part. Let us first see what the issue would be first.

Non-exported (private) function

A non-exported function would be something like the secret function in this file:

// foo.js
let secret = () => '🤫'
export function foo() {
  return secret();
}

Now, if we were to test for baz in our unit test,

// foo.test.js
import secret from './foo.js'

// secret is undefined

javascript

What is Geek Coin

What is GeekCash, Geek Token

Best Visual Studio Code Themes of 2021

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

Hire dedicated JavaScript Developers who are proficient in AngularJS, ReactJS, NodeJS, & VueJS frameworks. Get flexible hiring models as per your business requirements.

What is JavaScript - Stackfindover - Blog

What is PHP: - Who invented PHP, how it works, answers to all such questions about PHP, and much other information, you are going to

JavaScript Shopping Cart - Javascript Project for Beginners

JavaScript Shopping Cart - javascript shopping cart tutorial for beginnersBuy me a coffee 🍺 https://www.paypal.com/paypalme/ziddahSource Code: https://bit....

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Learn JavaScript - Full Course for Beginners. DO NOT MISS!!!

In this video tutorial, we'll learn Learn JavaScript - Full Course for Beginners. This complete 134-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript programming language. DO NOT MISS!!!