question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

automocking: true is broken

See original GitHub issue

Do you want to request a feature or report a bug?

Bug

What is the current behavior?

Running this in my tests:

import { enums } from './index';

describe('test', () => {
  it('should not blow up ', () => {
    expect(true).toEqual(true);
  });
});

Here is what my index.js looks like

//Lots of other imports
...
export const enums = {
  Foo: 'foo',
};
... 
// Lot's of other things

Here is what happens when I run jest:

 FAIL  src/modules/foo/index.spec.js
  ● Test suite failed to run

    TypeError: Cannot read property 'role' of undefined

      29 |               }
      30 |
    > 31 |               return `${foo}/${bar.splice(0, 1)[0]}`;
      32 |             }
      33 |
      34 |             return `${foo}/${bar}`;

      at Object.<anonymous> (src/utils/fooHelper.js:31:31)
      at Object.<anonymous> (src/modules/baz/index.js:58:20)
      at Object.<anonymous> (src/modules/bar/index.js:50:18)
      at Object.<anonymous> (src/modules/foo/index.js:66:13)
      at Object.<anonymous> (src/modules/foo/index.spec.js:3:14)

So given that I can’t use automocking: false, I tried setting it to true which gives this error:

 FAIL  src/modules/foo/index.spec.js
  ● Test suite failed to run

    Failed to get mock metadata: /Users/emmettharper/Dev/foo/node_modules/core-js/library/modules/_global.js

    See: http://facebook.github.io/jest/docs/manual-mocks.html#content

      at Runtime._generateMock (node_modules/jest-runtime/build/index.js:498:15)
      at Object.<anonymous> (node_modules/core-js/library/modules/_export.js:1:103)
      at Object.<anonymous> (node_modules/core-js/library/modules/_iter-define.js:3:15)

Setting:

    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/core-js"
    ]

Also just presents another error:

 FAIL  src/modules/bar/components/__tests__/bar.spec.js
  ● Test suite failed to run

    TypeError: Cannot set property 'DEFAULT_TIMEOUT_INTERVAL' of undefined

      at Object.<anonymous>.exports.create (node_modules/jest-jasmine2/build/jasmine/jasmine_light.js:40:31)

And setting unmocking jest-jasmine2 doesn’t seem to fix it.

If the current behavior is a bug, please provide the steps to reproduce and either a repl.it demo through https://repl.it/languages/jest or a minimal repository on GitHub that we can yarn install and yarn test.

run node scripts/test.js --env=jsdom

What is the expected behavior?

Ideally I could just grab a simple enum from a file with out jest resolving everything (I have a massive app). But if that’s too complicated then I would love for automock to work out of the box.

Please provide your exact Jest configuration

// package.json
  "jest": {
    "automock": true,
    "collectCoverageFrom": ["src/**/*.{js,jsx}"],
    "setupFiles": ["<rootDir>/scripts/testPolyfills.js"],
    "setupTestFrameworkScriptFile": "<rootDir>/scripts/setupTests.js",
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.js?(x)",
      "<rootDir>/src/**/?(*.)(spec|test).js?(x)"
    ],
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.jsx$": "babel-jest",
      "^.+\\.js$": "babel-jest",
      "^.+\\.css$": "<rootDir>/scripts/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/scripts/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "node_modules/(?!(redux-persist|@pivotusventures/vip-ui-components|react-select)/)"
    ],
    "modulePaths": ["<rootDir>/src"],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^src(.*)$": "<rootDir>/src$1"
    },
    "moduleFileExtensions": ["web.js", "mjs", "js", "json", "web.jsx", "jsx", "node"],
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/core-js",
      "<rootDir>/node_modules/jest-jasmine2"
    ]
  }


// scripts/setupTests.js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

const localStorageMock = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  removeItem: jest.fn(),
  clear: jest.fn(),
};

global.localStorage = localStorageMock;

configure({ adapter: new Adapter() });


// scripts/testPolyfills.js
'use strict';

if (typeof Promise === 'undefined') {
  // Rejection tracking prevents a common issue where React gets into an
  // inconsistent state due to an error, but it gets swallowed by a Promise,
  // and the user has no idea what causes React's erratic future behavior.
  require('promise/lib/rejection-tracking').enable();
  window.Promise = require('promise/lib/es6-extensions.js');
}

// fetch() polyfill for making API calls.
require('whatwg-fetch');

// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');

// In tests, polyfill requestAnimationFrame since jsdom doesn't provide it yet.
require('raf').polyfill(global);


// scripts/test.js
'use strict';

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({ silent: true });

const jest = require('jest');
const argv = process.argv.slice(2);

// Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
  argv.push('--watch');
}

jest.run(argv);

Run npx envinfo --preset jest in your project directory and paste the results here

Environment:
  OS: macOS Sierra 10.12.6
  Node: 8.9.4
  Yarn: 1.3.2
  npm: 5.6.0
  Watchman: 4.9.0
  Xcode: Xcode 9.2 Build version 9C40b
  Android Studio: 3.1 AI-173.4697961

Thanks!

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:16
  • Comments:19

github_iconTop GitHub Comments

3reactions
maxammanncommented, Sep 1, 2019

I’m having the same problem. Here is another error that can occure:

    TypeError: Cannot read property 'default' of undefined

      at node_modules/react-native/Libraries/vendor/emitter/EventSubscription.js:15:21
      at Object.<anonymous> (node_modules/react-native/Libraries/vendor/emitter/EventSubscription.js:22:2)
      at Object.require (node_modules/react-native/Libraries/vendor/emitter/EmitterSubscription.js:13:27)

Maybe that helps to make this issue better queryable 😃

1reaction
eliw00dcommented, Aug 28, 2022

The note on the automock config says:

Node modules are automatically mocked when you have a manual mock in place (e.g.: mocks/lodash.js). More info here.

Which is also broken: https://github.com/facebook/jest/issues/12777

So, I think in general automocking has had a lot of regressions.

Read more comments on GitHub >

github_iconTop Results From Across the Web

The Jest Object
Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. JavaScript ......
Read more >
How to automock a module with Jest and make assertions ...
mock("../api") doesn't give me any variables to assert/expect against. So, currently, I find I have to do this by. importing the actual module ......
Read more >
Mocking | Guide
Automocking algorithm #. If your code is importing a mocked module, without any associated __mocks__ file or factory for this module, Vitest ...
Read more >
How to Mock without Providing an Implementation in ...
Although it's technically true that a mock just needs to have the same ... method breaks tests saveOffer: (offer: Offer) => Promise<void>; }....
Read more >
Mocking modules in Jest
If you would like to un-mock a file and read the real source code instead of ... Note: You can also use the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found