blankface
blankface

Reputation: 6347

Mocking functional component in jest throws "Invalid variable access" error

I tried mocking a functional component (that uses Hooks) the following way:

jest.mock('./common/MyComp', () => () => <div>MockedMyComp</div>);

But its throwing this error:

 file.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
    Invalid variable access: React
    Whitelisted objects: Array, ArrayBuffer, Boolean, DataView, Date, Error, EvalError, Float32Array, Float64Array, Function, Generator, GeneratorFunction, Infinity, Int16Array, Int32Array, Int8Array, InternalError, Intl, JSON, Map, Math, NaN, Number, Object, Promise, Proxy, RangeError, ReferenceError, Reflect, RegExp, Set, String, Symbol, SyntaxError, TypeError, URIError, Uint16Array, Uint32Array, Uint8Array, Uint8ClampedArray, WeakMap, WeakSet, arguments, expect, jest, require, undefined, console, DTRACE_NET_SERVER_CONNECTION, DTRACE_NET_STREAM_END, DTRACE_HTTP_SERVER_REQUEST, DTRACE_HTTP_SERVER_RESPONSE, DTRACE_HTTP_CLIENT_REQUEST, DTRACE_HTTP_CLIENT_RESPONSE, COUNTER_NET_SERVER_CONNECTION, COUNTER_NET_SERVER_CONNECTION_CLOSE, COUNTER_HTTP_SERVER_REQUEST, COUNTER_HTTP_SERVER_RESPONSE, COUNTER_HTTP_CLIENT_REQUEST, COUNTER_HTTP_CLIENT_RESPONSE, global, process, Buffer, clearImmediate, clearInterval, clearTimeout, setImmediate, setInterval, setTimeout, __core-js_shared__.
    Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with `mock` are permitted.

I've seen a lot of examples mock components this way so I expected it to work in my case too.

Upvotes: 4

Views: 4279

Answers (1)

skyboyer
skyboyer

Reputation: 23705

so don't use JSX in mock declaration. Init it with jest.fn() and later provide mocked value.

...
import MyComp from './common/MyComp';
...

jest.mock('./common/MyComp', () => jest.fn());
// jest.mock('./common/MyComp'); will work as well

it ('...', () => {
 MyComp.mockReturnValue(<div>MockedMyComp</div>);

If you use Enzyme consider using shallow() instead of mount() then you would not need mocking subcomponents like above.

Upvotes: 2

Related Questions