繁体   English   中英

测试requireJS方法与Jasmine异步

[英]Testing requireJS methods async with Jasmine

我正在尝试使用jasminerequirejs测试需要模块的函数。 这是一个虚拟代码:

define("testModule", function() {
    return 123;
});
var test = function() {
    require(['testModule'], function(testModule) {
        return testModule + 1;
    });
}
describe("Async requirejs test", function() {
    it("should works", function() {
        expect(test()).toBe(124);
    });
});

它失败了,因为它是一个异步方法。 我该如何用它进行测试?

注意:我不想更改我的代码,只是我的测试describe功能。

对于异步的东西检查的测试runs() waits()waitsFor()

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

虽然这种方式看起来有点难看,因此您也可以考虑以下选项。

1.我建议你尝试jasmine.async ,它允许你以这种方式编写异步测试用例:

// Run an async expectation
async.it("did stuff", function(done) {
    // Simulate async code:
    setTimeout(function() {
        expect(1).toBe(1);
        // All async stuff done, and spec asserted
        done();
    });
});

2.也可以在里面运行测试require的回调:

require([
    'testModule',
    'anotherTestModule'
], function(testModule, anotherTestModule) {

    describe('My Great Modules', function() {

        describe('testModule', function() {
            it('should be defined', function() {
                expect(testModule).toBeDefined();
            });
        });

        describe('anotherTestModule', function() {
            it('should be defined', function() {
                expect(anoterTestModule).toBeDefined();
            });
        });
    });
});

3.另一点是我猜这个代码没有按照您的预期运行:

var test = function() {
    require(['testModule'], function(testModule) {
        return testModule + 1;
    });
};

因为如果你调用test() ,它将不会返回testModule + 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM