首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Mocha测试需要Node API的自定义模块?“无法读取未定义的属性'require‘”

如何使用Mocha测试需要Node API的自定义模块?“无法读取未定义的属性'require‘”
EN

Stack Overflow用户
提问于 2019-04-18 03:38:33
回答 1查看 531关注 0票数 1

我正在构建一个电子应用程序。我正在设置Mocha和Spectron的测试。摩卡在这条线上出错了

代码语言:javascript
复制
const filebrowser = require("../src/filebrowser.js")

具体地说,当我尝试请求节点的fs模块时,它在第2行的filebrowser模块中失败:

代码语言:javascript
复制
const {remote} = require('electron');
const fs = remote.require('fs');

我想这与Electron中的主进程/渲染器进程作用域有关,但我不知道如何让它在Mocha中正常工作。当我的模块依赖于Node api时,我该如何在Mocha测试文件中正确地要求它们?

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

代码语言:javascript
复制
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

代码语言:javascript
复制
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){}
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-18 21:05:25

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55734857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档