如果`beforeEach`中的代码是异步的,如何测试Jasmine中的方法?

Fre*_*ind 20 javascript unit-testing asynchronous jasmine

我正在尝试用Jasmine编写一些测试,但是现在有一个问题,如果有一些代码是异步的beforeEach.

示例代码如下所示:

describe("Jasmine", function() {

    var data ;

    beforeEach(function(){
        console.log('Before each');
        getSomeDataFromRemote(function(res){
            data = res;
        });
    });

    it("test1", function() {
        expect(data).toBe(something);
        console.log('Test finished');
    });

});
Run Code Online (Sandbox Code Playgroud)

你可以看到,beforeEach我希望从远程获取一些数据,并将其分配给data异步.

但是test1当我试图验证时:

 expect(data).toBe(something);
Run Code Online (Sandbox Code Playgroud)

数据是undefined,因为getSomeDataFromRemote尚未完成.

怎么解决?

Aar*_*ell 25

就像it你内部的异步内容一样,你可以在beforeEach中使用runswaitsFor:

define( 'Jasmine' , function () {
    var data ;

    beforeEach(function(){
        runs( function () {
            getSomeDataFromRemote(function(res){
                data = res;
            });
        });

        waitsFor(function () { return !!data; } , 'Timed out', 1000);
    });

    it("test1", function() {
        runs( function () {
              expect(data).toBe(something);
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

虽然我会假设这是因为这是测试代码,我认为你应该getSomeDataFromRemote在你的内部调用,it因为那实际上是你正在测试的;)

您可以在我为异步API编写的一些测试中看到一些更大的示例:https://github.com/aaronpowell/db.js/blob/f8a1c331a20e14e286e3f21ff8cea8c2e3e57be6/tests/public/specs/open-db.js

  • 在Jasmine中已停止等待和运行.现在,您可以使用done().希望这有帮助 - http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support (3认同)

Tim*_*gus 16

茉莉花2.0

要小心,因为在新的Jasmine 2.0中,这将改变,它将是摩卡风格.你必须done()beforeEach()和中使用函数it().例如,假设您想使用jQuery在LAMP服务器中测试页面是否存在且不为空$.get.首先,您需要将jQuery添加到SpecRunner.html文件中,并在您的spec.js文件中:

describe('The "index.php" should', function() {
    var pageStatus;
    var contents;

    beforeEach(function (done) {
        $.get('views/index.php', function (data, status) {
            contents = data;
            pageStatus = status;
            done();
        }).fail(function (object, status) {
            pageStatus = status;
            done();
        });
    });

    it('exist', function(done) {
        expect(status).toBe('success');
        done();
    });

    it('have content', function(done) {
        expect(contents).not.toBe('');
        expect(contents).not.toBe(undefined);
        done();
    });
});
Run Code Online (Sandbox Code Playgroud)

如您所见,您将该函数done()作为参数传递给beforeEach()it().当您运行测试时,在调用函数it()之前不会启动,因此在您收到服务器的响应之前,您不会启动预期.done()beforeEach()

该页面存在

如果页面存在,我们从服务器的响应中捕获状态和数据,然后我们调用done().然后我们检查状态是否"成功"以及数据是否为空或未定义.

该页面不存在

如果页面不存在,我们从服务器的响应中捕获状态,然后我们调用done().然后我们检查状态是否"成功"以及数据是否为空或未定义(必须是因为文件不存在).

  • 为什么```````被传递到```````函数并被调用?如果从```````中省略它们会出什么问题? (2认同)