我尝试通过以下方式模拟功能组件(使用 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.
我已经看到很多示例以这种方式模拟组件,所以我希望它也适用于我的情况。
最佳答案
所以不要在模拟声明中使用 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()
那么你就不需要像上面那样模拟子组件了。
关于reactjs - 开 Jest 中的模拟功能组件抛出 "Invalid variable access"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57213361/