jasmine.js预期()异步回调里面不起作用 [英] jasmine.js expect() does not work inside an asynchronous callback

查看:255
本文介绍了jasmine.js预期()异步回调里面不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我结识茉莉花( http://pivotal.github.com/jasmine/ ),并发现了一些莫名其妙的:

I'm getting acquainted with Jasmine (http://pivotal.github.com/jasmine/) and found something rather baffling:

it("should be able to send a Ghost Request", function() {
  var api = fm.api_wrapper;

  api.sendGhostRequest(function(response) {
    console.dir('server says: ', response);
  });

  expect(true).toEqual(false);
});

未能如预期。

Fails as expected.

然而,移动回调内部的期望呼叫:

However, moving the expect call inside the callback:

it("should be able to send a Ghost Request", function() {
  var api = fm.api_wrapper;

  api.sendGhostRequest(function(response) {
    console.dir('server says: ', response);
    expect(true).toEqual(false);
  });
});

不知怎的通过:0

Somehow passes :O

在一些调试: api.sendGhostRequest()做一个异步Ajax请求,和茉莉冲过去要求完成之前。

After some debugging: api.sendGhostRequest() does an asynchronous ajax request, and jasmine rushes past before the request has completed.

因此​​,问题:

我如何获得茉莉花等待AJAX​​执行确定的测试结果之前?

How do I get jasmine to wait for ajax execution before ascertaining the test result?

推荐答案

看一看 waitsFor()运行()上的茉莉花网站的标题下 异步支持的。

使用运行和waitsfor应强制茉莉花等待Ajax调用完成或某些超时。

Use of runs and waitsfor should force Jasmine to wait for the ajax call to finish or for some timeout.

在code看起来像:

it("should be able to send a Ghost Request", function() {
    runs(function() {
        api.sendGhostRequest(function(response) {
            console.dir('server says: ', response);
            flag = true;
        });
    }, 500);

    waitsFor(function() {
        return flag;
    }, "Flag should be set", 750);

    runs(function() {
        expect(true).toEqual(false);
    });
}

在这种情况下,期望将失败。

In which case the expect would fail.

这篇关于jasmine.js预期()异步回调里面不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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