我的应用程序有一个正常运行的 Jest/Flow 设置。我们切换到 TypeScript,我的所有测试都失败了。我将所有内容都转换为 .ts 和 .test.ts 并修复了所有错误。出于某种原因,我的 __mocks__
都不再使用了。 (我不得不模拟一些无法自动模拟的模块)
例如,下面的代码用于在需要时随时模拟电子,并允许代码调用模拟对话框,以便我可以检查错误情况是否报告了错误。自从我转换为 TypeScript 以来,任何时候 require ("electron")
在测试中被命中,它都会失败,说 remote is undefined。
例如)aFile.test.ts
import reportError from "../aFile.ts";
const { dialog } = require ("electron").remote;
describe ("reportError", () =>
{
test ("creates dialog", () =>
{
const title = "foo";
const message = "bar";
reportError (title, message);
expect (dialog.showErrorBox).toHaveBeenLastCalledWith (title, message);
});
});
例如)aFile.ts
const { dialog } = require ("electron").remote;
export default function reportError (title: string, message: string)
{
dialog.showErrorBox (title, message);
}
ex) __mocks__/electron.js
(node_modules 的兄弟)
module.exports = { remote: { dialog: { showErrorBox: jest.fn () } } };
我确定没有使用模拟,因为当我将以下内容添加到任何失败的 .test.ts 文件时,它开始通过:
jest.mock ("electron", () => { return { remote: { dialog: { showErrorBox: jest.fn () } } } });
为什么 TypeScript 找不到我的 __mocks__
?
最佳答案
我使用了以下解决方法来解决此问题:
创建mocks.js
:
jest.mock ("electron", () =>
{
return { remote: { dialog: { showErrorBox: jest.fn () } } };
});
在 package.json 中将其添加到 jest 部分(您的 mocks.js 所在的路径):
"jest":
{
"setupFiles": [ "<rootDir>/../mocks.js" ]
},
这将全局模拟电子,以及您在此处声明的任何其他模块,类似于拥有 __mocks__
文件夹。您或许可以将每个模块放在其自己的文件中并添加到 setupFiles 数组。
关于typescript - 开 Jest typescript 不使用 __mocks__ 作为 node_modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772844/