简体   繁体   中英

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

Implementing jest snapshot tests in an electron-react app i run into an error:

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

I can't find any way to get the tests working when a React component contains electron navite elements such as shell, Menu, MenuItem .

I have tried passing shell as a prop, as in the commented code in Home.spec.j s, but there is no change.

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

To keep the separation in your application I would propose that you don't mix up Electron and React parts. Depending on your application, two solutions could be:

  1. Use dispatchers to send events from your React components and run the actions from pure JS functions.
  2. Listen fornew-window event on the WebView you're rendering, and from that event run 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)
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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