electron - 如何使用 Mocha 测试需要 Node API 的自定义模块? "Cannot read property ' 需要'未定义的"

标签 electron mocha.js spectron

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

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

具体来说,当我尝试要求节点的 fs 模块时,它在第 2 行的文件浏览器模块中失败:
const {remote} = require('electron');
const fs = remote.require('fs');

我想这与 Electron 中的 Main 进程/Renderer 进程范围有关,但我不明白如何使它与 Mocha 一起正常工作。当 Mocha 测试文件依赖于我通常通过 Electron 远程模块访问的 Node 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/文件浏览器.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 应用程序的主进程中启动。这适用于端到端测试,但不适用于正常的模块测试。幸运的是,electron-mocha module 非常适合模块测试。它允许您指定从哪个进程运行测试,以及要包含在主进程中的任何模块。最重要的是它在 Chromium 中运行,因此您可以像往常一样访问应用程序的所有 API。

关于electron - 如何使用 Mocha 测试需要 Node API 的自定义模块? "Cannot read property ' 需要'未定义的",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55734857/

相关文章:

mongodb - 将 MongoDB 连接到 MERN 应用程序

javascript - 在 NodeJS 中创建一个返回查询结果作为回调的函数?

javascript - 检查 value 是 mocha/chai 测试中的字符串还是数字

electron - Spectron可用的方法无法正常工作

node.js - Electron 应用程序无法使用 `ffi-napi` 模块

javascript - 使用 Electron 和 Javascript 在控制台中显示完整文件夹路径

angular - 使用renderer.js和 Angular 组件使用的 Angular/Electron

javascript - 确保服务器应用程序在 mocha 测试开始之前运行

json - Spectron 测试产生 JScript 语法错误

typescript - 测试文件选择并在Spectron中上传