首页 > 解决方案 > 如何从节点 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。

任何帮助将不胜感激!

标签: javascriptjquerynode.jsajaxmocha.js

解决方案


这是不正确的:

module.exports = downloadRoles();

那是导出运行“downloadRoles()”的结果,显然不是你想要的。

导出这个:

module.exports.downloadRoles = mainWindow.downloadRoles; // no '()'

然后在您的测试页面中:

const { downloadRoles } = require('../js/mainWindow');
...
downloadRoles();

推荐阅读