javascript - 如何从节点 js 文件调用 vanilla JavaScript 函数
问题描述
我正在为一个普通的 JavaScript 文件 mainWindow.js 编写一些 mocha 单元测试。此 JS 文件创建 UI 组件并执行客户端调用后端 node.js 服务器以获取数据。我正在尝试编写的 mainWindow.spec.js 中的第一个测试是测试 mainWindow.js 中的 GET 函数。如何直接调用此函数?请参阅下面的片段。
主窗口.js
var mainWindow = {
downloadRoles: function (voiceInput) {
var word = voiceInput.procedureNumber;
var number = mainWindow.wordToNumber(word);
mainWindow.currentProcedure = mainWindow.mission[number - 1];
$.get({
url: mainWindow.urlprefix + "/hud/api/roles/" + mainWindow.currentProcedure,
dataType: "JSON"
})
.fail(function (error) {
console.log(error);
alert("Failed to download mission data");
})
.done(function (data) {
mainWindow.roles = data;
mainWindow.selectRole();
});
},
module.exports = downloadRoles();
mainWindow.spec.js
const assert = require('chai').assert;
var jsdom = require('jsdom');
var $ = require('jquery')(new jsdom.JSDOM().window);
var app = require('../js/mainWindow');
var mock = require('mock-require');
var sinon = require('sinon');
var passThrough = require('stream').PassThrough;
var http = require('http');
mock('jquery', $);
mock.reRequire('jquery');
describe('frontend client testing', function() {
beforeEach(function() {
this.request = sinon.stub(http, 'request');
});
afterEach(function() {
http.request.restore();
})
it('should initialize a window object', function() {
assert.typeOf(app, 'object');
})
it('should GET a JSON response', function(done) {
var expected = {};
var response = new PassThrough();
response.write(JSON.stringify(expected));
response.end();
var request = new PassThrough();
this.request.calls().returns(request);
app.downloadRoles();
})
})
更新 1
我正在导出 downloadRoles(),但是,在 mainWindow.spec.js 中调用它时,我收到错误 ReferenceError: downloadRoles is not defined。
任何帮助将不胜感激!
解决方案
这是不正确的:
module.exports = downloadRoles();
那是导出运行“downloadRoles()”的结果,显然不是你想要的。
导出这个:
module.exports.downloadRoles = mainWindow.downloadRoles; // no '()'
然后在您的测试页面中:
const { downloadRoles } = require('../js/mainWindow');
...
downloadRoles();
推荐阅读
- gitlab - 是否可以将 .env 推送到私有存储库;
- python - Pycharm中变灰的原因
- javascript - 如何删除各个网站未使用的 javascript
- mysql - 文本类型列未在 mysql 中按预期截断
- reactjs - 有没有一种方法可以使用我在 jsx 中声明的情感样式组件中的 js?
- html - 使用 BeautifulSoup4 从标签中获取标题属性
- asp.net - 使用必填字段验证器联系资源文件值
- node.js - Npm install 与本地依赖和 package-lock.json 抛出错误
- unit-testing - PowerMockito whenNew thenReturn 不工作
- .net - 带有 .net 框架的 gRPC 的 PEM 文件