如何解决Sinon withArgs 自定义匹配器
我正在尝试使用自定义匹配器来存根一个函数,该函数在我的 node.js 服务器的测试函数中执行两次。我正在测试的函数使用不同的参数两次使用 fs.readFileSync()
。我想我可以将 stub.withArgs()
与自定义匹配器一起使用两次来为两者返回不同的值。
let sandBox = sinon.createSandBox()
before(function(done) {
let myStub = sandBox.stub(fs,'readFileSync')
myStub.withArgs(sinon.match(function (val) { return val.includes('.json')})).returns('some json value')
myStub.withArgs(sinon.match(function (val) { return val.includes('.py')})).returns('some python value')
})
我面临的问题是,每当我存根 chai-http
时,在使用 fs.readFileSync()
测试我的休息端点时,我总是收到 400 状态代码。我的存根实现似乎阻止了 rest 端点甚至在 rest 端点内执行函数。当匹配器函数触发时,我可以(通过日志记录)验证它是否通过我的 node_modules
以查看是否有任何 fs.readFileSync()
函数需要返回替代值。
当我运行我的 mocha 测试时,在自定义匹配器中使用一些日志记录,我可以验证 node_modules
像 raw-body
有它们的 fs.readFileSync()
函数存根,但不应该返回替代值,因为匹配器返回 false
(因为参数没有通过我的匹配器)。但出于某种原因,我的 fs.readFileSync()
函数都没有被存根,甚至没有被执行,因为我的其余端点最终返回了 400 空响应。
在使用 fs.readFileSync
进行测试时,是否有一种特殊的方法可以存根 chai-http
之类的函数?我之前能够成功存根 fs.writeFileSync()
,但我无法存根 fs.readFileSync()
。
解决方法
我可以通过这个测试示例确认 stub.withArgs() 和 sinon matchers 工作。
// File test.js
const sinon = require('sinon');
const fs = require('fs');
const { expect } = require('chai');
describe('readFileSync',() => {
const sandbox = sinon.createSandbox();
before(() => {
const stub = sandbox.stub(fs,'readFileSync');
stub.withArgs(sinon.match(function (val) { return val.includes('.json')})).returns('some json value');
stub.withArgs(sinon.match(function (val) { return val.includes('.py')})).returns('some python value');
});
after(() => {
sandbox.restore();
});
it('json file',() => {
const test = fs.readFileSync('test.spec.json');
expect(test).to.equal('some json value');
});
it('python file',() => {
const test = fs.readFileSync('test.spec.py');
expect(test).to.equal('some python value');
});
it('other file',() => {
const test = fs.readFileSync('test.txt');
expect(test).to.be.an('undefined');
});
it('combine together',() => {
const test = fs.readFileSync('test.txt.py.json');
// Why detected as python?
// Because python defined last.
expect(test).to.equal('some python value');
});
});
当我使用 mocha 从终端运行它时:
$ npx mocha test.js
readFileSync
✓ json value
✓ python value
✓ other value
✓ combine together
4 passing (6ms)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。