【问题标题】:jest typescript not using __mocks__ for node_modules开玩笑的打字稿没有为 node_modules 使用 __mocks__
【发布时间】:2017-10-02 00:58:32
【问题描述】:

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

例如)aFile.ts

const { dialog } = require ("electron").remote;
export default function reportError (title: string, message: string)
{
   dialog.showErrorBox (title, message);
}

例如)__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__

【问题讨论】:

  • 我的猜测是 require('electron') 被 jest 解析器遮挡,并且在 jest 提升导入时未被检测到。这可能需要深入研究 jest 的来源。
  • 遇到同样的问题 :(
  • 我能够解决这个问题,我将在明天发布我的解决方法
  • @jonathanconway 希望发布的答案有所帮助
  • 您确定要正确导出模拟的模块定义吗?似乎您正在使用标准的 Javascript / CommonJS module.exports 表示法,我不确定这与 Typescript 的效果如何。我是否可以建议在 Typescript 中重写您的模拟,看看在没有您添加的 setupFiles 设置的情况下是否有效?

标签: typescript jestjs


【解决方案1】:

我使用以下解决方法来解决此问题:

创建mocks.js:

jest.mock ("electron", () => 
  {
     return { remote: { dialog: { showErrorBox: jest.fn () } } };
  });

在 package.json 中将这个添加到 jest 部分(你的 mocks.js 所在的路径):

"jest":
{
   "setupFiles": [ "<rootDir>/../mocks.js" ]
},

这将全局模拟电子以及您在此处声明的任何其他模块,类似于拥有__mocks__ 文件夹。您可能可以将每个模块放在自己的文件中并添加到 setupFiles 数组中。

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 2021-10-26
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2019-02-06
    • 2018-07-27
    相关资源
    最近更新 更多