Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda