jest打字稿不使用__mocks__用于node_modules

时间:2017-05-04 02:27:13

标签: typescript jestjs

我的应用程序有一个正常运行的Jest / Flow设置。我们切换到TypeScript,我的所有测试都破了。我将所有内容转换为.ts和.test.ts并修复了所有错误。出于某种原因,我的__mocks__都不再使用了。 (我不得不模拟一些未能自动锁定的模块)

例如,以下代码用于在需要时随时模拟电子,并允许代码调用模拟对话框,以便我可以检查错误情况报告错误。由于我转换为TypeScript,因此只要在测试中遇到require ("electron"),就会失败,说远程未定义。

ex)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);
   });
});

ex)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 () } } };

我确实知道mock没有被使用,因为当我将以下内容添加到任何失败的.test.ts文件时,它开始传递:

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

为什么TypeScript找不到我的__mocks__

1 个答案:

答案 0 :(得分:1)

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

创建mocks.js

jest.mock ("electron", () => 
  {
     return { remote: { dialog: { showErrorBox: jest.fn () } } };
  });
在package.json中将

添加到jest部分(mocks.js所在的路径):

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

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