Tec*_*nic 3 unit-testing jestjs electron
我为使用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
}
Run Code Online (Sandbox Code Playgroud)
我花了几天时间,但最终,我在这篇很棒的博客文章中找到了这个答案。引用:
Jest是从Node调用的,不会通过Webpack运行测试代码。相反,我们必须使用Jest的模拟功能用存根文件替换导入。
Jest有一个名为的帮助程序方法moduleNameMapper [object<string, string>]。从开玩笑的文档:
从正则表达式到模块名称的映射,该模块名称允许将资源(例如图像或样式)存入一个模块。
应该将其添加到package.json根对象中,如下所示:
{
"name": "My awesome app",
"jest": {
"moduleNameMapper": {
"electron": "<rootDir>/src/components/tests/mock/electron.js"
}
}
}
Run Code Online (Sandbox Code Playgroud)
以及模拟文件本身(/src/components/tests/mock/electron.js):
export const ipcRenderer = {
on: jest.fn()
};
Run Code Online (Sandbox Code Playgroud)
这样,您可以存根其他电子模块和方法(如上面博客中所示的remote)。
| 归档时间: |
|
| 查看次数: |
1660 次 |
| 最近记录: |