节点函数在请求完成之前返回'undefined',并具有所需的返回值



我知道 Node 是关于回调的。 在创建Jasmine测试时,我试图记住这一点,因为我更多地了解了Jasmine和Node。

我使用 jasmine-node 编写了一个非常基本的测试,它应该获取一个 HTML 页面,使用"cheerio"加载和解析返回的 HTML,并提取 HTML 元素的内容。 我的测试应该验证"cheerio"返回的文本的准确性。

发现我正在测试的函数在请求完成之前返回"未定义"。 您可以在测试的输出中看到这一点。 在测试报告失败后,您会看到控制台.log输出。

尝试使用回调来解决这个问题,并且我看到了有关使用"异步"等库的帖子。 我尝试使用 beforeEach() 来存储此数据以供测试。

我没有找到正确的食谱,我需要一些帮助。

索引.html

<!doctype html>
<html>
<body>
<span class="title">Title Goes Here</span>
</body>
</html>

模块1.js

var request = require('request');
var cheerio = require('cheerio');
exports.whoAmI = function () {
    'use strict';
    return "module1";
};
exports.testJq = function () {
    'use strict';
    var tipsotext = function (callback) {
        var output;
        request.get('http://localhost/test-test/index.html', function optionalCallback(err, httpResponse, body) {
            var $ = cheerio.load(body);
            output = $('.title').text();
            console.log("Executing callback with data: " + output);
            callback(null, output);
        });
    };
    tipsotext(function (err, data) {
        console.log("Returning with data: " + data);
        return data;
    });
};

模块 1 规范.js(我的测试)

var module1 = require("../src/module1.js");
describe("module1", function () {
    'use strict';
    it("should identify itself with whoAmI", function () {
        var test;
        test = module1.whoAmI();
        expect(test).toBe("module1");
    });
    it("should get data from the page", function () {
        var test;
        test = module1.testJq();
        expect(test).toBe("Title Goes Here");
    });
});

失败测试的输出

Failures:
  1) module1 should get data from the page
   Message:
     Expected undefined to be 'Title Goes Here'.
   Stacktrace:
     Error: Expected undefined to be 'Title Goes Here'.
    at null.<anonymous> (c:test-testspecmodule1-spec.js:14:22)
Finished in 0.011 seconds
2 tests, 2 assertions, 1 failure, 0 skipped
Executing callback with data: Title Goes Here
Returning with data: Title Goes Here
  tipsotext(function (err, data) {
    console.log("Returning with data: " + data);
    return data;
});

这个函数将数据返回给他的匿名函数 => 函数(err,data),因为这个方法是异步的,我认为你应该重新定义你的测试以支持异步方法,并向 testJq 函数添加一个回调参数。

重构,现在似乎可以工作了

我重新构建了我的模块和测试,使它们至少通过测试。 我不确定这是编写模块的最佳方式,但这是朝着正确方向迈出的一步,并演示了一种编写 Jasmine 测试的方法,该测试检查异步请求返回的值。

我的大部分更改都是从使用 Jasmine runs() 和 waitFor() 方法测试异步方法中产生的

我在这里做了很多菜鸟动作吗? 有建议解决任何问题的专业人士吗?

模块1.js

var request = require('request');
var cheerio = require('cheerio');
var title;
exports.whoAmI = function () {
    'use strict';
    return "module1";
};
exports.extractTitleFromBody = function (callback) {
    'use strict';
    request({
        url: 'http://localhost:63342/browserify-test/index.html', //URL to hit
        method: 'GET'
    }, function(error, response, body){
        if(error) {
            title = error;
        } else {
            var $ = cheerio.load(body);
            title = $('.title').text();
        }
        if (typeof callback === "function") {
            callback();
        }
    });
};
exports.getTitle = function () {
    'use strict';
    return title;
};

模块 1-规格.js

var module1 = require("../src/module1.js");
describe("module1", function () {
    'use strict';
    it("should identify itself with whoAmI", function () {
        var me;
        me = module1.whoAmI();
        expect(me).toBe("module1");
    });
    it("should make a real AJAX request and return the title", function () {
        var callback = jasmine.createSpy("spy");
        module1.extractTitleFromBody(callback);
        waitsFor(function() {
            return callback.callCount > 0;
        }, "The request timed out.", 5000);
        runs(function() {
            expect(callback).toHaveBeenCalled();
        });
        runs(function() {
            expect( module1.getTitle()).toBe("Title Goes Here");
        });
    });
});

最新更新