[英]sinon dependency function faking
I want to fake or stub a function which is not used as a method of an object.See mylib.js 我想伪造或存根未用作对象方法的函数。请参见mylib.js
//multiplicaiton.js //multiplicaiton.js
module.exports = function(x,y) {
return x*y;
}
//mylib.js //mylib.js
let Multiplication = require('./multiplication');
let myLib = function(x,y) {
var result = Multiplication(x,y)
return result
}
module.exports = myLib;
//test.js //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);
})
})
If you want to globally replace a module you need to use a link seam , which basically injects a different module (for instance a Sinon spy) instead of the real one. 如果要全局替换模块,则需要使用链接缝 ,该链接缝基本上是注入其他模块(例如Sinon间谍)而不是实际的模块。 You can see a whole how-to in the Sinon documentation .
您可以在Sinon文档中看到完整的操作方法 。
For your case it would be something like 对于您的情况,它将类似于
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);
})
})
I used Sinon fakes here, but you can use spies or stubs if you prefer them. 我在这里使用了锡农的假货,但如果您愿意,可以使用间谍或存根。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.