如果您真的想要存根Error 构造函数,您可以使用the Node.js global namespace:
code.js
exports.func = function() {
return new Error('error message');
}
code.test.js
const { func } = require('./code');
const sinon = require('sinon');
const assert = require('assert');
describe('func', function () {
it('should create an Error', function () {
const errorStub = sinon.stub(global, 'Error'); // <= stub the global Error
errorStub.callsFake(function(message) { // <= use callsFake to create a mock constructor
this.myMessage = 'stubbed: ' + message;
});
const result = func();
errorStub.restore(); // <= restore Error before doing anything else
assert(result.myMessage === 'stubbed: error message'); // Success!
sinon.assert.calledWithExactly(errorStub, 'error message'); // Success!
});
});
如果您这样做,您将需要在执行任何其他操作之前恢复 Error...即使断言也可以使用 Error,因此原始的 Error 需要到位,以防断言失败。
只监视Error 会更安全:
const { func } = require('./code');
const sinon = require('sinon');
describe('func', function () {
it('should create an Error', function () {
const errorSpy = sinon.spy(global, 'Error'); // <= spy on the global Error
func();
sinon.assert.calledWithExactly(errorSpy, 'error message'); // Success!
errorSpy.restore();
});
});
...最终,被测代码的孤立程度是有限的。对于像 Error 这样低级别的东西,您可能希望将其完全保持原样并使用 Chai 的 .throw 断言之类的东西来测试抛出的 Error。