我有一个函数A,它从函数B获取一个值,并将其与一个字符串进行比较。如果匹配,则返回true,否则返回false。
function A(random) {
var something = B();
if (random === something) {
return true;
} else {
return false;
}
}
function B() {
var something = 'hello';
return something;
}
我的测试如下所示
test("Test ", function () {
//Arrange
var expected = true;
var random = "hi";
var B = sinon.stub();
B.returns(random);
//Act
var actual = A('hi');
//Assert
deepEqual(actual, expected);
});
我已经使用Sinon成功地清除了函数B以返回我选择的值。当我在测试中直接调用函数B时,它会返回存根值,但是当我调用函数A时,它不再返回存根值,你知道为什么吗?
发布于 2016-09-01 09:53:44
您实际上并不是在存根A
或B
函数,而是创建一个具有相同名称的新本地函数。
如果你想注入(替换)函数,你必须以一种更加测试驱动的方式重构你的代码(即使用对象,不使用本地函数,dependency inversion...)。
或者使用像rewire
这样的工具来修改本地模块范围的变量并注入存根/假的变量。
即
// same as require, but create a new copy (not cached)
// with __set__ and __get__ methods:
var myModule = rewire('./myModule')
, stubbedB = sinon.stub();
myModule.__set__("B", stubbedB);
myModule.__get__("A");
发布于 2020-04-03 03:12:10
你可以做一些重构,这样你就不需要像rewire
这样的其他包了。
例如。
index.js
function A(random) {
const something = exports.B();
if (random === something) {
return true;
} else {
return false;
}
}
function B() {
const something = 'hello';
return something;
}
exports.A = A;
exports.B = B;
index.test.js
const mod = require('./');
const sinon = require('sinon');
const { expect } = require('chai');
describe('39266915', () => {
afterEach(() => {
sinon.restore();
});
it('should return true', () => {
sinon.stub(mod, 'B').returns('hi');
const actual = mod.A('hi');
expect(actual).to.be.true;
});
it('should return false', () => {
sinon.stub(mod, 'B').returns('hello');
const actual = mod.A('hi');
expect(actual).to.be.false;
});
});
单元测试结果和覆盖率报告:
39266915
✓ should return true
✓ should return false
2 passing (9ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 75 | 100 | 50 | 75 |
index.js | 75 | 100 | 50 | 75 | 11,13
----------|---------|----------|---------|---------|-------------------
源代码:https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/39266915
https://stackoverflow.com/questions/39266915
复制相似问题