javascript - JS 测试中间件正在返回 next()

标签 javascript unit-testing middleware sinon restify

我有一个像这样的中间件类

// code.js
function validation(req, res, next) {
    if (validationLogic(req)) {
        res.send(400);
        return next(false);
    }
    return next();
}

// code.test.js
describe('validation', () => {
    describe('when req is valid', () => {
        //setting up req, res, next stub

        //some other test

        //HERE IS MY QUESTION, how do I text that validation returns next(), and not next(false)
        it('return next(), and next() is called exactly once', () => {
            const spy = sinon.spy();
            nextStub = spy;
            const result = validation(reqStub, resStub, nextStub);
            assert(spy.calledOnceWithExactly());
            assert(result === nextStub()); // both of this
            assert(result === nextStub(false)); // and this line passed
        });
    });
});

我试图测试我的 validation 函数是否返回 next() 而不是 next(false)。但是在测试中,似乎只有assert(spy.calledOnceWithExactly())可以测试next中的参数。但是 assert(result === nextStub()) 后面的行除了结果实际上来自函数 next()

之外不能测试任何东西

assert(spy.calledOnceWithExactly()) 是否足够,或者是否有其他测试方法?

最佳答案

您不需要使用 spy 。您始终可以创建一个接受参数的“占位符”函数并将其替换为下一个,并确保该函数没有返回 false

it('return next(), and next() is called exactly once', () => {
    const nextStub = (arg) => (arg === false ? arg : 'I was called!');
    const result = validation(reqStub, resStub, nextStub);
    
    assert(result !== false);
    assert(result === 'I was called!');
});

类似的东西可能会起作用。或者如果你真的想使用 spy ,你可以检查 spy 的返回值和 spy 被调用的内容。确保您的 spy 函数可以接受参数。

https://sinonjs.org/releases/v7.0.0/spy-call/

关于javascript - JS 测试中间件正在返回 next(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52980387/

相关文章:

python - 在运行多面测试之前,如何使用 python 正确执行全局固定装置?

c++ - 关于 RCF 中间件二进制大小

node.js - Mongoose find 和 findOne 中间件不工作

javascript - 开始使用 JavaScript 进行游戏开发。 JS 和服务器语言之间的界限在哪里

javascript - 无法加载媒体(CODE:4 MEDIA_ERR_SRC_NOT_SUPPORTED)

javascript - 未捕获 : Bootstrap's JavaScript requires jQuery

clojure - 分解环形中间件场景

javascript - 如何在后台页面使用本地存储打开/关闭chrome扩展?

python - 学习 Django 单元测试

unit-testing - 你在编写单元测试时最常犯的错误是什么?