Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

86
Vistas
Mocha.js - How to save a global variable?

I'm working with Mocha.js for testing in a Node.js - Express.js - Firebase

I need a token from Firebase to access the API endpoints, I have a before hook in all my files, but after about 250 tests, probably calling the authentication endpoint multiple times, I'm getting rate limited by firebase.

I want to get the token once and use it in all my tests.

The tests are spread in different files, I have an index.js that requires them all. I'm aware of Root Level Hooks, but how can I save the token and use it in all my separate files?

Thanks!

7 months ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

you can create a function that gets the token. then call it. then create your test suite only after that

function getToken(callback) {
  //
}

// define tests
function allTests(token) {
    describe(xxxxxx, function () {
        it(xxxxxxxxx, function() {
            //
        })
    });
}

// start all
getToken(function(token) {
    allTests(token);
});

7 months ago · Juan Pablo Isaza Denunciar

0

  • Create a JSON file in your test root directory.
  • Import the file.
  • Append a token property with the token value.
  • Then import it anywhere to access the token property .
7 months ago · Juan Pablo Isaza Denunciar

0

I managed to solve it myself, if anyone needs an answer on how to approach it, take a look at this.

I have multiple files where we write our unit testing, we unite them in an index.spec.js that we execute for testing ($ mocha index.spec.js)

I created a utility file that looks like this:

let token;
(() => { token = getYourToken() })()
module.exports = {
getToken: () => {
    return new Promise((resolve) => {
        const interval = setInterval(() => {
            if (token) {
                clearInterval(interval);
                resolve(token);
            }
        }, 100);
    });
}
};

Basically, it's a singleton, in the index.spec.js I require this file, executing the 'getYourToken()' once (add your logic to get token here). Then I store it in a variable that then I export. In the export, I use an interval because my current code is not using promises, use your best practice method, interval + Promise worked for me.

This way I require this file in my tests and get the token I got at the beginning once, avoiding rate-limiting and any issue with firebase.

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos