在玩笑中模拟功能组件会引发“无效的变量访问”错误
Posted
技术标签:
【中文标题】在玩笑中模拟功能组件会引发“无效的变量访问”错误【英文标题】:Mocking functional component in jest throws "Invalid variable access" error 【发布时间】:2019-12-04 09:42:29 【问题描述】:我尝试通过以下方式模拟一个功能组件(使用 Hooks):
jest.mock('./common/MyComp', () => () => <div>MockedMyComp</div>);
但是它抛出了这个错误:
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.
我已经看到很多这样的模拟组件示例,所以我希望它也能在我的情况下工作。
【问题讨论】:
【参考方案1】:所以不要在模拟声明中使用 JSX。用jest.fn()
初始化它,然后提供模拟值。
...
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>);
如果您使用 Enzyme,请考虑使用 shallow()
而不是 mount()
,那么您将不需要像上面那样模拟子组件。
【讨论】:
执行mockReturnValue
会引发Property 'mockReturnValue' does not exist on type...
错误。另外,在我的 div 中返回一个 div 和 jest.mock('./common/MyComp');
有什么区别?以上是关于在玩笑中模拟功能组件会引发“无效的变量访问”错误的主要内容,如果未能解决你的问题,请参考以下文章