4

I am trying to test a function that requires a module using jasmine and requirejs. Here is a dummy code:

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

It fails, because it is an async method. How can I perform a test with it?

Note: I dont want to change my code, just my tests describe function.

4

1 回答 1

4

用于测试异步内容检查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

于 2013-05-17T19:44:07.080 回答