javascript - 如何在 Jest 中为 ipcRenderer.on 和 ipcRenderer.send 编写单元测试?

标签 javascript reactjs jestjs electron enzyme

您好,我正在使用 Electron 和 React 开发一个项目,

我在 react 端有一个表单,在提交时调用 ipcRenderer.on 一个 ipcRenderer.send 方法。

我在为表单提交功能编写单元测试代码时遇到困难。函数如下。

  handleFormSubmit = () => {
    const ethData = this.state.data;
    ipcRenderer.on('asynchronous-reply', (event, arg) => {
      if (arg === 'success') {
        this.setState({ status: true });
      }
    });
    ipcRenderer.send('update', value);
  }

首先,我只是想测试单击保存按钮时是否调用了handleFormSubmit 函数。 我写的是 -

it('calls handleFormSubmit method when the form is submitted', () => {
  const instance = wrapped.instance();
  wrapped.find('button').simulate('click');
  expect(instance.handleFormSubmit()).toHaveBeenCalled();
});

我收到的错误是

TypeError: Cannot read property 'on' of undefined.

最佳答案

这是单元测试解决方案:

index.jsx:

import React, { Component } from 'react';
const { ipcRenderer } = require('electron');

class SomeComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { data: '', status: false };
  }
  handleFormSubmit = () => {
    const ethData = this.state.data;
    const value = 'value';
    ipcRenderer.on('asynchronous-reply', (event, arg) => {
      if (arg === 'success') {
        this.setState({ status: true });
      }
    });
    ipcRenderer.send('update', value);
  };
  render() {
    return <form onSubmit={this.handleFormSubmit}></form>;
  }
}

export default SomeComponent;

index.test.jsx:

import { shallow } from 'enzyme';
import React from 'react';
import SomeComponent from '.';
const { ipcRenderer } = require('electron');

jest.mock(
  'electron',
  () => {
    const mElectron = { ipcRenderer: { on: jest.fn(), send: jest.fn() } };
    return mElectron;
  },
  { virtual: true },
);

describe('59934084', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<SomeComponent></SomeComponent>);
  });
  it('should render', () => {
    expect(wrapper.exists).toBeTruthy();
  });

  it('should handle submit, set status to true', () => {
    ipcRenderer.on.mockImplementationOnce((event, callback) => {
      callback(event, 'success');
    });
    wrapper.find('form').simulate('submit');
    expect(wrapper.state('status')).toBeTruthy();
    expect(ipcRenderer.on).toBeCalledWith('asynchronous-reply', expect.any(Function));
    expect(ipcRenderer.send).toBeCalledWith('update', 'value');
  });
  it('should handle submit without setting status to true', () => {
    ipcRenderer.on.mockImplementationOnce((event, callback) => {
      callback(event, 'failure');
    });
    wrapper.find('form').simulate('submit');
    expect(wrapper.state('status')).toBeFalsy();
    expect(ipcRenderer.on).toBeCalledWith('asynchronous-reply', expect.any(Function));
    expect(ipcRenderer.send).toBeCalledWith('update', 'value');
  });
});

100%覆盖率的单元测试结果:

 PASS  src/stackoverflow/59934084/index.test.jsx (14.089s)
  59934084
    ✓ should render (22ms)
    ✓ should handle submit, set status to true (14ms)
    ✓ should handle submit without setting status to true (4ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.jsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        16.114s, estimated 19s

如果您安装了 electron 节点,则无需将 { virtual: true } 选项传递给 jest.mock() 方法模块。只需将其删除即可。我使用此选项的原因是我没有安装 electron 节点模块并为您制作一个示例。

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59934084

关于javascript - 如何在 Jest 中为 ipcRenderer.on 和 ipcRenderer.send 编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59934084/

相关文章:

javascript - 如何将以下内容绑定(bind)到按钮单击事件上的本地 this 上下文变量?

javascript - 为什么下面的代码会出现循环引用错误?以及如何解决?

javascript - React.cloneElement/HOC/嵌入

reactjs - 配置 next.config 文件

javascript - 在类里面开 Jest 测试胖箭缺少这个

node.js - 意外的 Node 类型错误 SequenceExpression with jest

javascript - 开 Jest – 导出问题 { 默认为

javascript - innerHTML 返回带有文本的 NaN

javascript - HTML 音频 - 我如何检测流是否可用?

javascript - reactjs onClick 处理程序未附加在 Windows 8 和 7 上的 IE11 上