To test exported function, you can simply import it. But what about non-exported functions? Well that’s easy too, thanks to Rewire!

Testing Non-Exported Functions in JavaScript

Recently, I finally integrated unit testing into my startup project. I’ve settled with Jest

, I’ll speak more about this in a separate journal entry. While writing my test, I ran into a bit of a dilemma of trying to write unit tests for non-exported functions 😖

Contents

  • Testing Exported Function
  • Non-export function
  • Introducing Rewire
  • Installing Rewire for a Vue app
    • Step 1: Install package
    • Step 2: Add to babel config
    • Step 3: Using it
  • Non-exported function must be called in Exported Function
  • Warning! Vuex with Rewire
    • 1. My Problematic Code
    • 2. The solution
    • Alternative solutions
  • Proficiency leads to Result!
  • Beginner Friendly Resources
    • Unit testing in JavaScript Part 1 - Why unit testing?
    • Jest Crash Course - Unit Testing in JavaScript
  • Resources

Testing Exported Function

It’s super straightforward to test exported functions.

// utils.js
export function sayHi() {
  return '👋';
}

And a unit test could be something like this:

// utils.test.js

import { sayHi } from './utils.js';

describe('sayHi', () => {
  it('returns wave emoji', () => {
    expect(sayHi()).toBe('👋');
  });
});

Non-export function

Now, what if the function is not exported?

function saySecret() {
  return '🤫';
}

Ah yikes, there is no way to test it! 🤷‍♀️

// utils.test.js

// ❌
import { saySecret } from './utils.js';

saySecret; // undefined

Introducing Rewire

And then I discover this nifty package called Rewire

! Here’s their official description:

Rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may

  • inject mocks for other modules or globals like process
  • inspect private variables
  • override variables within the module.

The second point is exactly what I needed!

Installing Rewire for a Vue app

Instead of using rewire, I used a package called babel-plugin-rewire. Which is essentially ES6 version of rewire, so I can use import. Here’s their description:

It is inspired by rewire.js and transfers its concepts to es6 using babel.

Unit testing in JavaScript Part 1 - Why unit testing?

Jest Crash Course - Unit Testing in JavaScript

#javascript #testing #web-development #programming #developer

Testing Non-Exported Functions in JavaScript
29.80 GEEK