繁体   English   中英

使用 Jest 对 Electron-React 应用程序进行单元测试,TypeError:无法匹配“未定义”或“空”

[英]Unit-testing Electron-React app with Jest, TypeError: Cannot match against 'undefined' or 'null'

electron-react应用程序中实现jest快照测试时遇到错误:

类型错误:无法匹配“未定义”或“空”。

React组件包含诸如shell, Menu, MenuItem类的electron导航元素时,我找不到任何方法来使测试正常工作。

我曾尝试将shell作为道具传递,就像Home.spec.j中的注释代码一样,但没有任何变化。

主页.js

import React, { Component } from 'react';
import { remote } from 'electron';
const { shell } = remote;

export default class Home extends Component {
    openLink() {
        shell.openExternal('https://www.facebook.com')
    }

    render() {
        return (
            <div>
                <button onClick={() => this.openLink()}>
                    Open External
                </button>
            </div>
        )
    }
}

主页.spec.js

import React from 'react';
import renderer from 'react-test-renderer';

import Home from '../../app/components/Home';

// import { remote } from 'electron'
// const { shell } = remote;

describe('Counter component', () => {
    it('should render snapshot', () => {
        const component = renderer.create(
            <Home />
            //<Home shell={shell} />
        )
        const tree = component.toJSON()
        expect(tree).toMatchSnapshot()
    })
});

为了在您的应用程序中保持分离,我建议您不要混淆 Electron 和 React 部分。 根据您的应用程序,两种解决方案可能是:

  1. 使用调度程序从 React 组件发送事件并从纯 JS 函数运行操作。
  2. 侦听您正在渲染的 WebView 上的新窗口事件,并从该事件运行openExternal

来自电子的例子

const {shell} = require('electron')
const webview = document.querySelector('webview')

webview.addEventListener('new-window', (e) => {
  const protocol = require('url').parse(e.url).protocol
  if (protocol === 'http:' || protocol === 'https:') {
    shell.openExternal(e.url)
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM