开玩笑 - 用“模拟”前缀模拟不起作用
Posted
技术标签:
【中文标题】开玩笑 - 用“模拟”前缀模拟不起作用【英文标题】:Jest - mocking with 'mock' prefix not working 【发布时间】:2020-10-01 09:13:23 【问题描述】:我想模拟某个模块的功能,但即使在阅读这里https://github.com/facebook/jest/issues/9730#issuecomment-606512664 之后,我仍然收到错误:
代码:
const mockGetPermissions = getPermissions: jest.fn()
jest.mock('./MyModule', () => mockGetPermissions)
控制台:
The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
Invalid variable access: _get__
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, console, expect, isNaN, jest, parseFloat, parseInt, require, undefined, globalThis, BigUint64Array, BigInt64Array, BigInt, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, escape, unescape, eval, isFinite, SharedArrayBuffer, Atomics, WebAssembly, global, process, GLOBAL, root, Buffer, URL, URLSearchParams, TextEncoder, TextDecoder, clearInterval, clearTimeout, setInterval, setTimeout, queueMicrotask, clearImmediate, setImmediate, __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` (case insensitive) are permitted.
但我添加了“模拟”前缀..为什么它不起作用?
【问题讨论】:
你没有显示你的设置,问题是特定的。你可能会注意到Invalid variable access: _get__
指的是 Babel rewire 插件。不要将它与 Jest 一起使用。
@EstusFlask 我不熟悉这个错误,但是在你发表评论后我得到了这个gitmemory.com/issue/speedskater/babel-plugin-rewire/223/…我该如何解决?
不要使用 babel-plugin-rewire。在 Jest 设置中不需要它。
【参考方案1】:
嘲讽
如果你想模拟 getPermissions
方法,你可以这样做:
const mockGetPermissions = jest.fn();
jest.mock('./MyModule', () => (
getPermissions: () => mockGetPermissions();
))
测试
it('should call the getPermissions when I call the implementation', () =>
weirdMethodWhereYouCallGetPermissionsInside();
expect(getPermissions).toHaveBeenCalled();
);
【讨论】:
以上是关于开玩笑 - 用“模拟”前缀模拟不起作用的主要内容,如果未能解决你的问题,请参考以下文章