如何在使用sinon的回调中测试回调?

时间:2019-02-18 02:24:29

标签: javascript node.js unit-testing callback sinon

我正在尝试使我的验证码覆盖率达到100%。

现在,我所缺少的是这一行:

$('.sub-type').prop('multiple', false).attr('name', 'sub_type').select2();

(err, result) => this.processDBResult(err, result, id, req, res, CLASS_NAME, METHOD_NAME, stopwatch)

我该如何进行呢?

我尝试类似的东西:

 (accounttype) => globUtil.getConfig(accounttype, constant.BOOK,
            source => this.generateData(req, res, stopwatch, className, methodName, result, source))

但是它总是会返回成功,我知道我的getIdSpy.callsFake(() => { sinon.assert.callCount(processDBResultSpy, 4); }); 不会被叫4次,只会叫一次。

代码:

processDBResultSpy

测试用例:

exports.getBookInfo = (req, res) => {

    let stopwatch = globUtil.startStopWatch();

    const METHOD_NAME = "getBookInfo";

    const id = req.params.id;
    const params = [id];

    if (globUtil.isId(id)) {
        bookDao.getBookById(params,
            (err, result) => this.processDBResult(err, result, id, req, res, CLASS_NAME, METHOD_NAME, stopwatch));

    } else {
        bookDao.getBookBySelfId(params,
            (err, result) => this.processDBResult(err, result, id, req, res, CLASS_NAME, METHOD_NAME, stopwatch));
    }
};

 exports.processDBResult = (err, result, id, req, res, className, methodName, stopwatch) => {

    if (err) {
        log.error(err);

        this.generateErrorResponse(req, res, 500, err, stopwatch, className, methodName);

        return;
    }

    if (result.length == 0) {
        log.info("No results");
        this.generateErrorResponse(req, res, 404, format(message.NOT_FOUND, id), stopwatch, className, methodName)

        return;
    }

    globUtil.getAccountType(id,
        (accounttype) => globUtil.getConfig(accounttype, constant.BOOK,
            source => this.generateData(req, res, stopwatch, className, methodName, result, source)));
}

1 个答案:

答案 0 :(得分:0)

最后得到了答案。我所做的是我产生了我的方法。

it('1. getBookInfo - called with id', (done) => {
        let getIdSpy = sinon.stub(bookDao, "getBookById").yields(null, []);
        let getSelfIdSpy = sinon.stub(bookDao, "getBookBySelfId");
        let processDBResultSpy = sinon.stub(controller, "processDBResult");

        let request = httpMocks.createRequest({
            method: 'GET',
            url: constant.MODULE_URL,
            params: {
                id: 'BOOKID'
            }
        });

        let response = httpMocks.createResponse();
        controller.getHdbInfo(request, response);

        sinon.assert.callCount(getIdSpy, 1);
        sinon.assert.callCount(getSelfIdSpy, 0);

        //how do i proceed form here
        sinon.assert.callCount(processDBResultSpy, 1);

        done();
    });