用Jasmine测试callback

最近写点js代码,试着用了下jasmine。自己写的一个函数用callback来传数据,最后需要合并到async的调用链中去,但是在写测试的时候没找到怎么写的(最后发现是思维定式了,看到解决方案就会知道了),也不知道是自己没找对关键字还是咋地,反正就是没找到相关的代码。不过最后在洗了个澡后试出来了东西,记在这吧~


先是源代码,简化一个版本了:

function foobar(content, callback) {
    if (!content.includes('foobar')) {
        callback("Content doesn't contain needed word!");
    } else {
        callback(null, content.replace('foobar', 'aloha'));
    }
}

module.exports = {
    extractGpsData: extractGpsData,
    foobar: foobar
};

下面是测试代码

'use strict';

describe('Foobar', function() {

    var foobarHelper = require('foobar_helper');

    describe('foobar', function() {
        it('raises error if no foobar provided.', function(done) {
            foobarHelper.foobar('hello world', function(err, content) {
                expect(err).not.toEqual(null);
                expect(content).toEqual(undefined);
                expect(err).toContain('needed word');
                done();
            });
        });

        it('replaces foobar to aloha if foobar provided.', function(done) {
            foobarHelper.foobar('foobar world', function(err, content) {
                expect(err).toEqual(null);
                expect(content).not.toEqual(null);
                expect(content).toContain('aloha');
                done();
            });
        });

    });
});

主要是之前的代码都是 expect(func).toBe(XXX) 的形式,所以开始有点懵了。后来想想把callback加进去然后在callback里面测试就ok了。嗯,刚看jasmine不到1小时,就这样先用着吧,嘿嘿。

你可能感兴趣的:(用Jasmine测试callback)