Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"expect is not defined" when importing jest-enzyme in setup.js #86

Closed
andriichernenko opened this issue May 17, 2017 · 12 comments
Closed
Labels

Comments

@andriichernenko
Copy link

I am using Jest 20 with Enzyme 2.8.0.

Importing jest-enzyme in my test files works, but as soon as I put it in my setup.js I am getting the following error:

    ReferenceError: expect is not defined
      
      at Object.<anonymous> (node_modules/jest-enzyme/lib/index.js:23:1)

Here's my setup.js file:

/* eslint-disable no-console */

require('jest-enzyme');
require('react-native-mock-render/mock');
const { jsdom } = require('jsdom');

global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
	if (typeof global[property] === 'undefined') {
		global[property] = document.defaultView[property];
	}
});


const { Response, Headers, Request } = require('whatwg-fetch');

global.Response = Response;
global.Headers = Headers;
global.Request = Request;


jest.mock('Linking', () => ({
	addEventListener: jest.fn(),
	removeEventListener: jest.fn(),
	openURL: jest.genMockFn().mockReturnValue(Promise.resolve()),
	canOpenURL: jest.genMockFn().mockReturnValue(Promise.resolve()),
	getInitialURL: jest.genMockFn().mockReturnValue(Promise.resolve()),
}));

jest.mock('react-native-snackbar', () => ({
	LENGTH_LONG: 1,
	LENGTH_SHORT: 1,
	LENGTH_INDEFINITE: 1,
}));


const originalConsoleError = console.error;
console.error = (message) => {
	// see https://github.com/Root-App/react-native-mock-render/issues/6
	if (message.startsWith('Warning: Unknown prop')) {
		return;
	}

	originalConsoleError(message);
};

I tried rolling back to Jest 19 and putting the import at the end of file, didn't help.
What could be the problem?

@blainekasten
Copy link
Collaborator

Could you try upgrading to 3.1.0?

@andriichernenko
Copy link
Author

I had 3.1.1, downgrading to 3.1.0 didn't fix the problem.

@blainekasten
Copy link
Collaborator

@andriichernenko did you figure this out? I honestly have no clue why your environment would be doing that.

@andriichernenko
Copy link
Author

@blainekasten no, I did not. I ended up not using jest-enzyme in my project. I guess this issue can be closed.

@blainekasten
Copy link
Collaborator

blainekasten commented Jun 27, 2017

Ah, sorry about this. Wish I could help more! Thanks for trying it out

@michaelgmcd
Copy link

michaelgmcd commented Jul 2, 2017

Hey @andriichernenko, I stumbled across this myself trying to use the jest-glamor-react package. If you want to extend expect, you must do it in the file specified by setupTestFrameworkScriptFile in your jest config and not setupFiles. i.e:

// expect will not be defined in these files
"setupFiles": ["<rootDir>/config/polyfills.js"],
// but it will be defined in this file.
"setupTestFrameworkScriptFile": "<rootDir>/config/jest/setup.js"

Let me know if that helps.

@mulholo
Copy link
Contributor

mulholo commented Jan 29, 2019

For anyone stumbling across this in 2019, @michaelgmcd's answer works but Jest's setupTestFrameworkScriptFile has been replaced by setupFilesAfterEnv

@blainekasten
Copy link
Collaborator

@mulholio interested in submitting a PR to update docs?

@Dispersia
Copy link

If you're still having the issue after the above, try updating your node version. We were attempting against node 10, and it did not pass, but upgrading to 13 fixed.

@GiladR1979
Copy link

I followed this guide and finally it worked:
https://medium.com/@hdsenevi/unit-testing-in-react-native-with-jest-and-enzyme-40cd7dabb6f1

@ghasemikasra39
Copy link

I am facing the same issue:
jest.config.js

module.exports = {
  preset: 'react-native',
  collectCoverage: true,
  moduleDirectories: ['node_modules', 'src'],
  transform: {
    '^.+\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js',
  },
  setupFiles: ['<rootDir>setup-tests.js'],
  transformIgnorePatterns: ['node_modules/(?!(jest-)?react-native)'],
  coveragePathIgnorePatterns: ['/node_modules/', '/jest'],
  testEnvironment: 'jsdom',
};

setup-tests.js

import 'react-native';
import 'jest-enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Enzyme from 'enzyme';

/**
 * Set up DOM in node.js environment for Enzyme to mount to
 */
const {JSDOM} = require('jsdom');

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const {window} = jsdom;

function copyProps(src, target) {
  Object.defineProperties(target, {
    ...Object.getOwnPropertyDescriptors(src),
    ...Object.getOwnPropertyDescriptors(target),
  });
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
};
copyProps(window, global);

/**
 * Set up Enzyme to mount to DOM, simulate events,
 * and inspect the DOM in tests.
 */
Enzyme.configure({adapter: new Adapter()});

Env.

   "enzyme": "^3.11.0",
    "enzyme-adapter-react-16": "^1.15.2",
    "babel-jest": "^24.9.0",
    "jest": "^26.0.1",
    "jest-enzyme": "^7.1.2",
    "jsdom": "^16.2.2",

@ealemda2
Copy link

Same issue, fixed by upgrading node v10.10 --> v10.15 (see original comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

8 participants