测试方法requireJS茉莉异步 [英] Testing requireJS methods async with Jasmine

查看:137
本文介绍了测试方法requireJS茉莉异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试需要使用一个模块的茉莉花功能 requirejs
这是一个虚拟的code:

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?

注:我不想改变我的code,只是我的测试描述函数

推荐答案

有关异步的东西检查测试运行()等待() waitsFor()

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 我建议你尝试 jasmine.async ,可以让你编写异步测试案例是这样的:

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 您还可以运行在您的测试要求的回调:


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 还有一点就是我猜测,这code未工作作为你希望:


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

由于如果调用测试(),将不会返回 testModule + 1

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

这篇关于测试方法requireJS茉莉异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆