Unit testing Auth0 extension code

It is not obvious how to unit test Auth0 rule code. even if you're deploying it with the Auth0 Deploy CLI. You'll need to be using that to set up automated testing.

Auth0 expects rules to be uploaded in a very specific format, a single JavaScript function. Not exported in any way, just a single JavaScript function.  This makes it hard to test when running in Jest test runner environment.

The solution we used to overcome this was to wrap our function in a Self-Executing Anonymous Function. This function checks to see if module exists in the global object and exports in the case that it calls module.export if it doesn't exist it returns the function.

This allows us to write unit tests to confirm that our code works as expected, requires minimal extra code to maintain and the Auth0 Rule execution environment is able to execute our function.

N.B. if you are using the Auth0 configuration you'll need to provide a global object in your test code to test the use of these values.

The code ends up looking like:
/* global configuration */

(() => {
  function mySweetRuleCode(user, context, callback) {
     // Some sweet rules code
  if (module) { // module doesn't exist in the rules execution environment
    module.exports = addTokenData;
  return mySweetRuleCode; // return the function so the rules execution environment works.
})() /*prettier-ignore */ // eslint-disable-line semi

// Test
import mySweetRuleCode from "./mySweetRuleCode";
describe("tests", () => {
  global.configuration = {} // configuration values that are provided at runtime by rules environment
  // make sure it all works


Popular posts from this blog

Solving `Empty reply from server` in DotNet Core

Building a verify JWT function in TypeScript

Can't resolve DNS Aws