Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!