2017-10-23 9 views
1

Electron에서 실행중인 React (webpack 포함)로 빌드 된 프로젝트에 참여하고 있습니다. Jest을 사용하여 단위 테스트를 실행하면 오류 TypeError: Cannot read property 'on' of undefined과 함께 실패합니다 (테스트하지 않을 때, 예를 들어 전자로 실행).Electron + Jest - 유닛 테스트에서 ipcRenderer가 정의되지 않았습니다.

코드 :

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 
} 
+0

필자는 Webpack의 "target": "electron"또는 "target": "electron-renderer"를 추가하는 것을 포함하여 많은 다른 솔루션을 시도했지만 이러한 것들은 효과가 없습니다 – Technotronic

답변

2

그것은 나에게 몇 일을했다하지만 결국, 나는 this great blog post이 답을 발견했다. 제품 견적 :

Jest는 노드에서 호출되며 Webpack을 통해 테스트 코드를 실행하지 않습니다. 대신 Jest의 mocking 함수를 사용하여 가져 오기 을 스텁 파일로 대체해야합니다.

Jest에는 moduleNameMapper [object<string, string>]이라는 도우미 메서드가 있습니다. jest documentation에서 :

단일 모듈이있는 이미지 나 스타일과 같은 리소스를 스텁 아웃 할 수있는 정규 표현식에서 모듈 이름으로 매핑합니다.

그것은이처럼 package.json 루트 개체에 추가되어야

:

{ 
    "name": "My awesome app", 
    "jest": { 
    "moduleNameMapper": { 
     "electron": "<rootDir>/src/components/tests/mock/electron.js" 
    } 
    } 
} 

및 모의 파일 자체 (/src/components/tests/mock/electron.js) :

이렇게하면 다른 전자 모듈과 방법을 스터핑 할 수 있습니다 (위의 블로그에 표시된 것처럼 리모컨처럼).