gpt4 book ai didi

javascript - 使用 Jest 对 Electron-React 应用程序进行单元测试,TypeError : Cannot match against 'undefined' or 'null'

转载 作者:行者123 更新时间:2023-11-30 21:04:29 34 4
gpt4 key购买 nike

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

TypeError: Cannot match against 'undefined' or 'null'.

React 组件包含 electron navite 元素(如 shell、Menu、MenuItem)时,我找不到任何方法让测试正常工作.

我试过将 shell 作为 prop 传递,就像在 Home.spec.js 中的注释代码中一样,但没有任何变化。

Home.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>
)
}
}

Home.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. 监听 new-window您正在呈现的 WebView 上的事件,并从该事件运行 openExternal

Example from Electron :

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

关于javascript - 使用 Jest 对 Electron-React 应用程序进行单元测试,TypeError : Cannot match against 'undefined' or 'null' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46785179/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com