我想伪造或存根未用作对象方法的函数。请参见mylib.js
// multiplicaiton.js
module.exports = function(x,y) {
return x*y;
}
// mylib.js
let Multiplication = require('./multiplication');
let myLib = function(x,y) {
var result = Multiplication(x,y)
return result
}
module.exports = myLib;
// test.js
let sinon = require('sinon');
let mylib = require('./mylib');
let chai = require('chai');
let expect = chai.expect;
describe('My Test', function() {
it('Faking Globally',function() {
//How do I declare 'multiplication' as Globally and fake it.
expect(mylib(2,3)).to.deep.equal(6);
})
})
答案 0 :(得分:0)
如果要全局替换模块,则需要使用 link seam ,它基本上会注入 different 模块(例如Sinon间谍),而不是真正的模块。一。您可以看到a whole how-to in the Sinon documentation。
对于您的情况,它类似于
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const chai = require('chai');
const expect = chai.expect;
// replace the dependency with a stub
const multiplicationFake = sinon.fake.returns(42);
const mylib = proxyquire('./mylib', { './multiplication': multiplicationFake });
describe('My Test', function() {
it('Faking Globally',function() {
const result = mylib(2,3);
expect(multiplicationFake.calledOnce).to.equal(true);
expect(result).to.deep.equal(42);
})
})
我在这里使用了锡诺的假货,但如果您愿意,可以使用间谍或存根。