【发布时间】:2019-09-19 03:25:16
【问题描述】:
在第三方库上执行jest.Mock 时遇到以下错误。有问题的图书馆是react-email-editor。
jest.mock("react-email-editor", () => {
return {
Editor: <div>Email Editor</div>,
};
});
jest.mock 出错
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.
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.
如果我将其更改为doMock,我会得到:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
注意:由于我使用的是 Typescript,并且 react 电子邮件编辑器没有类型定义,因此我必须在我的项目根 .types/react-email-editor/index.d.ts 中创建一个存根定义文件,如下所示:
declare module "react-email-editor";
编辑:调用 jest.mock 之前的导入列表
import { act, fireEvent, render } from "@testing-library/react";
import * as React from "react";
import { EmailEditor, IEmailEditorProps } from "../EmailEditor"; // my wrapper around react-email-editor
import Editor from "react-email-editor";
【问题讨论】:
-
你在测试文件中导入
react-email-editor了吗? -
我确实喜欢
import Editor from "react-email-editor". I've read that due tojest.mock` 提升,导入必须在模拟之后进行......我已经尝试过了,但没有运气。 -
您能否编辑问题以将导入包含在导致 jest.mock 调用的测试中?
标签: reactjs jestjs react-testing-library