2

我正在使用jasmine 来测试 JavaScript 代码。
javascript 代码由使用 requireJs 加载的模块组成。 当我使用需要的 json requirejs-plugins
加载 json 文件时,我在 Web 浏览器上看不到任何输出。 奇怪的是我也没有收到任何 javascript 错误。text! plugin

这是我的代码(1)。

有任何想法吗?

PS:
不确定,但问题可能与时间延迟有关。
如果我从本地 ( time latency = 6ms) 获取文件,它就可以工作。
如果我从远程服务器 ( ) 获取文件(具有相同的本地内容),time latency = 170 ms它将显示一个空页面。
知道如何解决这个问题吗?


(1)

/*global define, window*/
(function () {
    'use strict';
    var specUrl = './';
    define([
        'jasmine',
        'jasmineHtml',
        'jasmineJquery',
        'json!json_data', // if I comment this line is ok, 
                          // otherwise I get empty page with no error
        specUrl + 'models/user.spec'
    ], function (jasmine) {
        var initialize = function () {
            // some code
        };

        return {
            initialize: initialize
        };
    });
}());

我确实阅读了有关异步规范的文档,但尚不清楚如何解决该问题。有任何想法吗?
我确实发布了一个非常简单的代码:(1)有效,(2)无效,因为从服务器获取 json_data 可能需要大约 250 毫秒。

(1)

    define([
        'appJasmine',
//        'json!json_data',
    ], function (app) {
        app.initialize(); // it display data on browser
    });

(2)

    define([
        'appJasmine',
        'json!json_data',
    ], function (app) {
        app.initialize(); // it does not display data on browser
    });
4

2 回答 2

1

查看 jasmine 文档中的异步调用,很可能会需要等待属性出现才能运行规范。

https://github.com/pivotal/jasmine/wiki/Asynchronous-specs

根据您更新的问题并阅读您提供的 jQuery 插件文档,问题很明显:

/**
 * Your App code
 */
var myTestObj = {};
define([
    // some stuff
], function () {
    // will be called when everything is ready
    myTestObj.loaded = true;
});


/**
 * Jasmine spec
 */

describe("My suite", function() {

    it("should run some test", function() {
        // waitsFor is called periodically and will only execute
        // the following run statement when it returns true
        // waiting will be aborted after 10 seconds in this example
        waitsFor(function() {
            return myTestObj.loaded;
        }, "Async modules to be loaded", 10000);

        runs(function() {
            expect(myTestObj.loaded).toBeTruthy();
        });
    });

});

这是一个非常基本的示例,但您应该了解原理。WaitsFor 定期检查条件,您可以在等待完成后使用运行语句执行。您可以使用 run 语句来包装 describe、it 或 expect 调用。

于 2012-07-17T22:29:49.980 回答
1

如果您在所有模块准备好之前运行 execJasmine,您将获得空白页面。
因此,您应该发布有关 execJasmine 调用的代码。
例如,如果您正在运行此代码:

        window.onload = function () {
            if (currentWindowOnload) {
                currentWindowOnload();
            }
            execJasmine();
        };

你会得到一个空页面。

如果你运行这个,它应该可以工作。

        setTimeout(function () {
            if (currentWindowOnload) {
                currentWindowOnload();
            }
            execJasmine();
        }, 0)
于 2012-07-18T08:02:49.457 回答