Asynchronous 使用Jasmine,如何测试异步调用的返回值?

Asynchronous 使用Jasmine,如何测试异步调用的返回值?,asynchronous,redis,jasmine,Asynchronous,Redis,Jasmine,我正在使用jasmine测试redis的功能。由于RedisAPI都是异步调用的,我不知道如何使用jasmineexpect().toBe()测试结果。我总是看到错误: throw err; ^ TypeError: Cannot call method 'expect' of null 以下是我的测试代码: var redis = require('redis'); describe("A suite for redis", fu

我正在使用jasmine测试redis的功能。由于RedisAPI都是异步调用的,我不知道如何使用jasmine
expect().toBe()
测试结果。我总是看到错误:

            throw err;
                  ^
TypeError: Cannot call method 'expect' of null
以下是我的测试代码:

var redis = require('redis');

describe("A suite for redis", function() {
    var db = null;

    beforeEach(function() {
        db = redis.createClient();
        // if you'd like to select database 3, instead of 0 (default), call
        // db.select(3, function() { /* ... */ });
        db.on("error", function (err) {
            console.log("Error " + err);
        });
    });

    afterEach(function() {
        db.quit();
    });

    it('test string', function(){
        db.set('str_key1', 'hello', redis.print);
        db.get('str_key1', function(err,ret){
            expect(ret).toBe('hello');
        });
    });
});
我看不到上面代码中定义了“val”,您可能需要检查“ret”


对于同步调用,可以使用Jasmine异步功能,将
done()
传递到
beforeach()
it()
,请参阅:

因此,您的代码可以更改为:

var redis = require('redis');

describe("A suite for redis", function() {
    var db = null;

    beforeEach(function(done) {
        db = redis.createClient();
        // if you'd like to select database 3, instead of 0 (default), call
        // db.select(3, function() { /* ... */ });
        db.on("error", function (err) {
            console.log("Error " + err);
        });
        done();
    });

    afterEach(function(done) {
        db.quit();
        done();
    });

    it('test string', function(done){
        db.set('str_key1', 'hello', redis.print);
        db.get('str_key1', function(err,ret){
            expect(ret).toBe('hello');
            done(); // put done() after expect(), or else expect() may report error
        });
    });
});

谢谢你的回答。我在这里发布代码时出错了。但这并不是主要原因,因为expect()上似乎出现了错误。
expect(ret).toBe('hello');
var redis = require('redis');

describe("A suite for redis", function() {
    var db = null;

    beforeEach(function(done) {
        db = redis.createClient();
        // if you'd like to select database 3, instead of 0 (default), call
        // db.select(3, function() { /* ... */ });
        db.on("error", function (err) {
            console.log("Error " + err);
        });
        done();
    });

    afterEach(function(done) {
        db.quit();
        done();
    });

    it('test string', function(done){
        db.set('str_key1', 'hello', redis.print);
        db.get('str_key1', function(err,ret){
            expect(ret).toBe('hello');
            done(); // put done() after expect(), or else expect() may report error
        });
    });
});