typescript - 开 Jest typescript 不使用 __mocks__ 作为 node_modules

标签 typescript jestjs

我的应用程序有一个正常运行的 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/

相关文章:

javascript - RxJS groupBy 未获取订阅值

angular - 将 JSON 数据限制为固定长度

javascript - Windows 10,运行 jest 时找不到现有的 binding.node 文件

node.js - 如何使用 Jest 断言数据类型

typescript - 如何使用 describe.each 为 jest 测试添加类型?

ReactJS 和 Typescript useContext - 类型上不存在属性

reactjs - 如何在 Jest 中向我的测试添加 <canvas> 支持?

reactjs - React.js : How to get all props component expects?

javascript - 在我的 nodejs 测试中自动化用户输入

javascript - 在 Typescript 中使用 javascript