jest: Dynamic require in yargs don't work in jest's environment

Reporting a bug

Using

What is the current behavior?

Tests fail with

    TypeError: require(...) is not a function
        at Object.self.help (/Users/tmcw/src/zeroarg/node_modules/yargs/lib/usage.js:155:30)
        at Object.self.showHelp (/Users/tmcw/src/zeroarg/node_modules/yargs/lib/usage.js:381:15)
        at Object.Yargs.self.showHelp (/Users/tmcw/src/zeroarg/node_modules/yargs/yargs.js:712:11)
        at /Users/tmcw/src/zeroarg/node_modules/yargs/yargs.js:1046:18
        at Array.forEach (native)
        at Object.Yargs.self._parseArgs (/Users/tmcw/src/zeroarg/node_modules/yargs/yargs.js:1041:27)
        at Object.Yargs.self.parse (/Users/tmcw/src/zeroarg/node_modules/yargs/yargs.js:533:23)

tested-module.test.js

jest.dontMock('yargs');
var path = require('path');
var testedModule = require('./tested-module');

test('empty', () => {
  testedModule( '--help')
});

tested-module.js

var yargs = require('yargs');

function testedModule(input) {
  yargs.help();
  yargs.usage(input);
}

module.exports = testedModule;

What is the expected behavior?

Tests would be able to load and use the yargs module. The failed line is this dynamic require in yargs

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

  • yarn: 0.22.0
  • jest: 19.0.2
  • macOS
  • node 7.8.0

Current jest config is:

"jest": {
    "automock": false
  }

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 16 (6 by maintainers)

Most upvoted comments

Seeing this too when trying to use le_node which uses codependency to optionally require different winston versions. Will update if I get a reproducible sample I can share.

Do you have a reproduction?

Can confirm in test project I posted it works! But introduced in my real project (jest: ^21.3.0-beta.4) still same issue. Wiped out npm_modules, cleared cache. Any advice how could I find out what is going on? What could have impact on this behaviour?

Looks like something does module.parent in your code.

My transpiled code from babel does not show any usage of .parent call (but it is a build from babel cli, test are run by jest on non transpiled code), so maybe this behaviour is caused by some node_module introduced in dependencies?