gpt4 book ai didi

javascript - sinon 监视功能不起作用

转载 作者:行者123 更新时间:2023-12-03 01:28:20 27 4
gpt4 key购买 nike

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

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
})
})

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

最佳答案

Sinon 无法更改现有函数的内容,因此它创建的所有 spy 都只是现有函数的包装器,用于计算调用次数、内存参数等。

因此,您的第一个示例等于:

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 中“监视”和“ stub ”的关键是您必须在测试中使用监视/ stub 函数。您的原始代码仅使用原始的非 spy 功能。

关于javascript - sinon 监视功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407877/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com