1

Circular dependences are one way of mocking child functions inside a parent in Jest.js. I've seen ES6 examples on how to use circular imports, but I'm having trouble translating this to ES5 syntax using require. Here's what I have:

const currentFile = require('./targetFile.js');

const a = () => {
  return currentFile.b();
};

const b = () => {
  return 'from b'
};

module.exports = { a, b }

I then attempt to run the above code in a tester file that requires the above as targetFile:

const targetFile = require("../targetFile.js");

test('a and b', () => {
  console.log(targetFile.a(), `=====targetFile.a()=====`);
});


 FAIL  views/admin/__tests__/targetFile.test.js
  ✕ a and b (12ms)

  ● a and b

    TypeError: currentFile.b is not a function

      26 | 
      27 | const a = () => {
    > 28 |   return currentFile.b();
         |                      ^
      29 | };
      30 | 
      31 | const b = () => {

What is the correct syntax for the above using requires (or other ES5 browser compatible syntax)?

Sean D
  • 3,810
  • 11
  • 45
  • 90

1 Answers1

1

For technical reasons, the module.exports = {} syntax does not work with circular dependencies. Fortunately you can use the exports.a = a syntax, and use it like const target = require('target');.... target.a();

In overall, circular imports is causing more headache than good, so I suggest avoiding them. I also fail to see why would you need circular imports for testing, and your example doesn't show it either. Could you post more detail about your files?

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
  • Thanks, will test this now. See the top answer on this SO for why to use circular imports with Jest: https://stackoverflow.com/questions/51269431/jest-mock-inner-function/55193363#55193363 – Sean D Jun 02 '19 at 09:43