How to do TDD on Auth0 scripts

Auth0 is a SaaS platform that offers a set of tools to implement Authentication and Authorization for your web, mobile and legacy applications.

This platform provides a great developer experience with a good documentation and innovative features, such as rules, JavaScript functions that are executed when a user authenticates to your application.

GitHub deployment extension

The GitHub Deployments extension allows you to deploy rules and database connection scripts from GitHub to Auth0.

You can configure a GitHub repository, keep all your rules and database connection scripts there, and deploy them automatically to Auth0 each time you push to your repository.

There are also extensions for GitLab or Bitbucket.

Problem with unit tests

I need TDD to express the behaviour of my scripts (article in french).

To write Unit Tests, you have to modularize your script to be able to import the function you want to test in your test.

But, with the extensions convention and this serverless platform, the scripts can only contain a single function.

Auth0 offers several testing strategies. You can find how to do Integration Tests, performance tests or how to mock Auth0. Nevertheless, none of them are intended for Unit Testing.

Solution to do TDD

My first thought was to read the file I want to test in a String, then execute an eval with it.

But I discover this article that explains you should use Function instead of eval.

The bonus of this method is that you can create a closure (article in french) which facilitate the injection of mocked dependencies.

So the solution is to add these lines to your tests :

const mockedDependency = require('some_dependency');

const fs = require('fs');
const scriptSource = fs.readFileSync('<path_of_the_source_script>', 'utf8');  // 1.
const testableScript = new Function('one_dependency', 'return ' + scriptSource + ';'); // 2.
const functionToUseInTests = testableScript(mockedDependancy); // 3.

These lines :

  1. read the script through the file system
  2. inject it in a new function with its dependencies (aka a closure)
  3. evaluate the closure with the mocked dependencies

So now you can TDD \o/

With an example on Github

If you want more details you can go to this repository and pay attention to these two commits that show the addition of two behaviours in two steps in accordance with the TDD principles.

Leave a Reply

Your email address will not be published. Required fields are marked *

This form is protected by Google Recaptcha