Electron + Jest - ipcRenderer在单元测试中未定义

时间:2017-10-23 20:43:27

标签: unit-testing electron jestjs

我正在为一个用Electron运行的React(带webpack)构建的项目做贡献。当使用Jest 执行单元测试时,它失败并显示错误TypeError: Cannot read property 'on' of undefined(并且在未测试时工作正常,例如使用Electron运行)。

代码:

import React, { Component } from 'react';
import { ipcRenderer } from  'electron';
// some more imports

class Setup extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // some state
    };

    ipcRenderer.on('open-file-reply', this.someMethod); // << fails on this line
  }
  // more class stuff
}

2 个答案:

答案 0 :(得分:5)

我花了几天时间,但最后,我在this great blog post找到了这个答案。引用:

  

从Node调用Jest并且不通过Webpack运行测试代码。   相反,我们必须使用Jest的模拟函数来替换导入   使用存根文件。

Jest有一个名为moduleNameMapper [object<string, string>]的辅助方法。来自jest文档:

  

从正则表达式到允许存根的模块名称的映射   资源,例如具有单个模块的图像或样式。

它应该添加到 package.json 根对象中,如下所示:

{
  "name": "My awesome app",
  "jest": {
    "moduleNameMapper": {
      "electron": "<rootDir>/src/components/tests/mock/electron.js"
    }
  }
}

和模拟文件本身(/src/components/tests/mock/electron.js):

export const ipcRenderer = {
  on: jest.fn()
};

这样你就可以存根其他电子模块和方法(比如上面博客中显示的遥控器)。

答案 1 :(得分:0)

另一种方法是在根文件夹electron.js中创建一个__mocks__文件。

electron.js应该看起来像

export const ipcRenderer = {
  on: jest.fn(),
};

您可以在https://jestjs.io/docs/en/manual-mocks#mocking-node-modules

阅读更多内容