Jasmine 单元测试中未分配全局变量

Global variable not being assigned in Jasmine unit test

我在 Jasmine 单元测试中遇到一些问题,将全局变量视为未定义。我正在使用 Squire 来模拟一些 classes 以及通过 RequireJS 注入的依赖项。这是我的单元测试的精简示例:

我的 'service' class (service.js)

define(['durandal/system', 'cache'],
    function (system, cache) {
        var dataservice = {

            retrieveData: function () {
                return cache.getCachedData();
            }
        };

        return dataservice;
});

我模拟 'cache' 依赖项的装置。

define(['Squire'], function (Squire) {
    var injector = new Squire();

    return {
        initialize: function () {
            injector.clean();

             injector.mock('cache', {
                getCachedData: function () {
                    return { item: "one" };
                }
            });

            return injector;
        }
    };
});

我的规格:

define(['dataservice_fixture', 'durandal/system'],
    function (testFixture, system) {
        var container = testFixture.initialize();
        var dataserviceModule;

        container.require(['service'], function (preparedDataservice) {
            dataserviceModule = preparedDataservice;
        });

        describe('The data service ', function () {
            it('should exist.', function () {
                expect(dataserviceModule).toBeDefined();
            });
        });
    });

在我的 'should exist' 测试中,dataserviceModule 未定义。我希望它会在我的固定装置(上面的容器)将其拉入时出现。现在,如果我在 define() 的规范顶部拉入 'service',并在那里设置 dataserviceModule,测试会看到它如定义。

为什么我的 container.require 要么没有将变量的范围设置得高一个范围,要么在那个范围和测试 运行 之间丢失了?我在提升时阅读了这个 this question,但我没有在我的 container.require.

中重新声明相同的变量名称

看起来这实际上是一个竞争条件,因为测试 运行 在我的模块可以加载之前进行。我添加了 waitsFor 和一个在我的模块加载后为真的闩锁来解决这个问题。

任何遇到的人,请查看http://www.htmlgoodies.com/beyond/javascript/test-asynchronous-methods-using-the-jasmine-runs-and-waitfor-methods.html