我的应用程序有一个功能正常的 Jest/Flow 设置。我们改用 TypeScript,我的所有测试都失败了。我将所有内容都转换为 .ts 和 .test.ts 并修复了所有错误。由于某种原因,我的都__mocks__不再使用了。(我不得不模拟一些无法自动模拟的模块)
例如,下面的代码用于在需要时模拟电子,并允许代码调用模拟对话框,以便我可以检查错误情况是否报告了错误。自从我转换为 TypeScript 以来,任何时候require ("electron")在测试中命中,它都会失败,说远程未定义。
前任)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);
});
});
Run Code Online (Sandbox Code Playgroud)
前任)aFile.ts
const { dialog } = require ("electron").remote;
export default function reportError (title: string, message: string)
{
dialog.showErrorBox (title, message);
}
Run Code Online (Sandbox Code Playgroud)
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 () } } };
});
Run Code Online (Sandbox Code Playgroud)
在 package.json 中将其添加到 jest 部分(mocks.js 所在的路径):
"jest":
{
"setupFiles": [ "<rootDir>/../mocks.js" ]
},
Run Code Online (Sandbox Code Playgroud)
这将全局模拟电子以及您在此处声明的任何其他模块,类似于拥有__mocks__文件夹。您可以将每个模块放入其自己的文件中并添加到 setupFiles 数组中。
| 归档时间: |
|
| 查看次数: |
2907 次 |
| 最近记录: |