功能上的sinon间谍无法正常工作

编程入门 行业动态 更新时间:2024-10-06 06:52:51
本文介绍了功能上的sinon间谍无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试为此简单的中间件功能编写独立测试

I'm trying to write a standalone test for this simple middleware function

function onlyInternal (req, res, next) { if (!ReqHelpers.isInternal(req)) { return res.status(HttpStatus.FORBIDDEN).send() } next() } // Expose the middleware functions module.exports = { onlyInternal }

这不起作用

describe('success', () => { let req = { get: () => {return 'x-ciitizen-token'} } let res = { status: () => { return { send: () => {} } } } function next() {} let spy before(() => { spy = sinon.spy(next) }) after(() => { sinon.restore() }) it('should call next', () => { const result = middleware.onlyInternal(req, res, next) expect(spy.called).to.be.true <-- SPY.CALLED IS ALWAYS FALSE EVEN IF I LOG IN THE NEXT FUNCTION SO I KNOW IT'S GETTING CALLED }) })

但是可以.

describe('success', () => { let req = { get: () => {return 'x-ciitizen-token'} } let res = { status: () => { return { send: () => {} } } } let next = { next: () => {} } let spy before(() => { spy = sinon.spy(next, 'next') }) after(() => { sinon.restore() }) it('should call next', () => { const result = middleware.onlyInternal(req, res, next.next) expect(spy.called).to.be.true }) })

为什么不仅仅监视功能正常工作?

Why isn't spying on just the function working?

推荐答案

Sinon无法更改现有函数的内容,因此它创建的所有间谍程序都只是对现有函数的包装,这些计数可以计数调用,记住args等.

Sinon cannot change content of existing function, so all spies it creates are just wrappers over existing function that count calls, memoize args etc.

因此,您的第一个示例与此相同:

So, your first example is equal to this:

function next() {} let spy = sinon.spy(next); next(); // assuming that middleware is just calling next // spy is not used!

您的第二个示例等于:

let next = { next: () => {} } next.next = sinon.spy(next.next); // sinon.spy(obj, 'name') just replaces obj.name with spy on it next.next(); // you actually call spy which in in turn calls original next.next //spy is called. YaY

因此,它们在sinon中间谍"和存根"的关键在于您必须在测试中使用间谍/存根功能.您的原始代码只是使用了原始的非间谍功能.

So, they key to 'spying' and 'stubbing' in sinon is that you have to use spied/stubbed function in test. Your original code just used original, non-spied function.

更多推荐

功能上的sinon间谍无法正常工作

本文发布于:2023-11-26 18:53:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634774.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法正常   间谍   功能   工作   sinon

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!