在Jasmine单元测试中没有分配全局变量

Global variable not being assigned in Jasmine unit test

本文关键字:分配 全局变量 Jasmine 单元测试      更新时间:2023-09-26

我在Jasmine单元测试中遇到一些未定义全局变量的问题。我使用Squire模拟一些类,通过RequireJS注入依赖。下面是我的单元测试的一个精简示例:

我的'service'类(service.js)

define(['durandal/system', 'cache'],
    function (system, cache) {
        var dataservice = {
            retrieveData: function () {
                return cache.getCachedData();
            }
        };
        return dataservice;
});

模拟'cache'依赖的fixture。

define(['Squire'], function (Squire) {
    var injector = new Squire();
    return {
        initialize: function () {
            injector.clean();
             injector.mock('cache', {
                getCachedData: function () {
                    return { item: "one" };
                }
            });
            return injector;
        }
    };
});

And my spec:

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();
            });
        });
    });

在我的'应该存在'测试中,dataserviceModule是未定义的。我希望它是虽然当我的夹具(上面的容器)把它拉进来。现在,如果我在define()的spec的顶部拉入'service',并在那里设置dataserviceModule,测试将其视为已定义。

为什么是我的容器。需要要么不设置变量一个范围更高,或丢失之间的测试运行?我读到这个关于提升的问题,但我没有在我的container.require.

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

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

如果有人遇到这种情况,请查看http://www.htmlgoodies.com/beyond/javascript/test-asynchronous-methods-using-the-jasmine-runs-and-waitfor-methods.html