mercredi 21 août 2019

How to access local variable in jest

Currently, I am trying to write a test. I want to use a local variable in the test, but unfortunately, I don't manage to mock or use it. The variable and the function which uses it, aren't exported.

How do I access the local variable authToken in utils.test.js? So I can change authToken to another value.

I've tried to use rewire (https://www.npmjs.com/package/rewire), but this didn't work. authToken is still undefined.

utils.js

const { auth } = require('./auth.js');

let authToken = undefined;

const checkIfTokenIsValid = async () => {
    if (authToken) {
        authToken = await auth();
    }
};

module.exports = {
    // some other functions
}

utils.test.js

const _rewire = require('rewire');
const utils = _rewire('../../lib/resources/utils');
utils.__set__('authToken', () => true);


describe('api auth', () => {
    // some tests
});

Aucun commentaire:

Enregistrer un commentaire