gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:26:08 25 4
gpt4 key购买 nike

我正在构建一个 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/

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