Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

252
Vistas
Can I mock undefined things with Rewire (and Jest), or is there another approach to unit-test non-exported functions with dependencies?

I'm adapting Jest to an old JS which consists of several js files and is built via concatenation (and is supposed to be run in browser). Some files use "globals" defined in others. To make Jest work, I've tested the Rewire package and got it working for no-dependency case like this:

// experiment.js
function sum(a, b) {
    return a + b
}

const myVar = 'some'


// experiment.test.js
const rewire = require('rewire')
const experimentRewired = rewire('./experiment.js')

const $sum = experimentRewired.__get__('sum')
const $myVar = experimentRewired.__get__('myVar')

test('sum gives 1 + 2 = 3', () => {
    expect($sum(1, 2)).toBe(3)
})

// not a real test, just shows that variables are loaded too
test('myVar is equal to string "some"', () => {
    expect($myVar).toBe("some")
})

This is a simple case when everything to be tested is inside a single file. What I'm trying to test now is issentially injecting a dependency from another file:

// globals.js – config should be injected into experiment.js
const config = {}

// experiment.js
config.name = 'value'

// experiment.test.js
const rewire = require('rewire')
const globalsRewired = rewire('./globals.js')
const experimentRewired = rewire('./experiment.js')

const $config = globalsRewired.__get__('config')
experimentRewired.__set__('config', $config)         // trying to inject
const $$config = experimentRewired.__get__('config')

test('config has .name', () => {
    expect($$config.name).toBeTruthy()
})

but this results in ReferenceError: config is not defined. I'm guessing that what happens is – experiment.js is called first and "injecting" would happen after it (if it were not the error before it).

Is there a way to "inject" the dependency or may be virtually concatenate the files without actually saving a new js file (which will be the last resort and is not desirable due to performance considerations)? Suggestions both with and without Rewire are welcome.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda