我需要一个Sinon匹配器,用于检查字符串是否以其他字符串结尾。我看到数组(sinon.match.array.endsWith)有类似的东西,但是为什么不是字符串呢?似乎很多人都需要...
经过进一步的挖掘,我发现@Bergi的评论实际上是正确的。实际上,我可以使用Javascript的本机String.endsWith函数并将其作为自定义匹配器传递给Sinon。
[不像在Sinon中具有内置的匹配器那样优雅,但是它可以解决问题。
这是一个可供参考的快速示例:
const foo = () => {
console.log('Chuck says hello.')
}
const sinon = require('sinon')
const consoleLogStub = sinon.stub(console, 'log')
describe('foo', () => {
it('should log a message that ends with " says hello!"', () => {
foo()
sinon.assert.calledWithExactly(
consoleLogStub,
sinon.match(
value => value.endsWith(' says hello!'),
'.endsWith(" says hello!")'
)
)
})
})
此测试将失败(因为记录的消息以点而不是感叹号结尾),并产生以下输出:
AssertError: expected log to be called with exact arguments
Chuck says hello. .endsWith(" says hello!")
at Object.fail (/Users/john/myProject/node_modules/sinon/lib/sinon/assert.js:106:21)
at failAssertion (/Users/john/myProject/node_modules/sinon/lib/sinon/assert.js:65:16)
at Object.assert.<computed> [as calledWithExactly] (/Users/john/myProject/node_modules/sinon/lib/sinon/assert.js:91:13)
at Context.<anonymous> (test2.js:12:16)
at processImmediate (internal/timers.js:439:21)