如何使用 Mocha 测试需要 Node API 的自定义模块? "Cannot read property 'require' of undefined"

How do I use Mocha to test my custom module that requires Node API? "Cannot read property 'require' of undefined"

我正在构建一个 Electron 应用程序。我正在使用 Mocha 和 Spectron 进行测试。 Mocha 在线出错

const filebrowser = require("../src/filebrowser.js")

具体来说,当我尝试要求节点的 fs 模块时,第 2 行的文件浏览器模块失败了:

const {remote} = require('electron');
const fs = remote.require('fs');

我想这与 Electron 中的 Main process/Renderer 进程范围有关,但我不明白如何使其与 Mocha 一起正常工作。当我的模块依赖于我通常通过电子远程模块访问的节点 api 时,我如何在 Mocha 测试文件中正确地要求它们?

test/test.js(这是来自 github 页面的 spectron 示例代码)。我通过 package.json 脚本(npm 测试)使用 "mocha" 命令 运行 它。请注意,我什至还没有为我的文件浏览器模块编写测试,它在 require 语句上失败了。

const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron') // Require Electron from the binaries included in node_modules.
const path = require('path')
const filebrowser = require("../src/filebrowser.js")

describe('Application launch', function () {
  this.timeout(10000)

  beforeEach(function () {
    this.app = new Application({
      path: electronPath,

      // use the main.js file in package.json located 1 level above.
      args: [path.join(__dirname, '..')]
    })

    return this.app.start()
  })

  afterEach(function () {
    if (this.app && this.app.isRunning()) {
        return this.app.stop()
    }
  })

  it('shows an initial window', function () {
    return this.app.client.getWindowCount().then(function (count) {
        assert.equal(count, 1)
    })
  })
})

src/filebrowser.js

const {remote} = require('electron');
const fs = remote.require('fs');
const Path = require('path');

module.exports = {        
    //note that I would be calling fs functions in here, but I never get that far because the error happens on remote.require('fs')
    determineFiletype: function(currentDirectory, fileName){}
}

经过更多研究,Spectron 似乎无法做到这一点。 Spectron 在 Webdriver 进程中启动,而不是在电子应用程序的主进程中启动。这适用于端到端测试,但不适用于正常的模块测试。幸运的是,electron-mocha 模块非常适合模块测试。它允许您指定 运行 从哪个进程进行测试,以及要包含在主进程中的任何模块。最重要的是它 运行 在 Chromium 中,因此您可以像往常一样访问应用程序的所有 API。