Testing requireJS methods async with Jasmine

南笙酒味 提交于 2019-12-10 16:47:57

问题


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.


回答1:


For testing of an asynchronous stuff check runs(), waits() and waitsFor():

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

Though this way looks a bit ugly as for me, therefore you could also consider following options.

1. I'd recommend you to try jasmine.async that allows you to write asynchronous test cases in this way:

// 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. Also you can run your tests inside require's callback:

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. Another point is I guess that this code is not working as you're expecting:

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

Because if you call test(), it won't return you testModule + 1.



来源:https://stackoverflow.com/questions/16552815/testing-requirejs-methods-async-with-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!