【发布时间】:2021-03-15 12:12:08
【问题描述】:
A.js
const func2 = () => 'world';
module.exports = {func2}
Util.js
const {func2} = require("./A");
const func1 = () => {
return 'hello ' + func2(); // <= use the module
}
module.exports = { func1 }
Util.test.js
const sinon = require('sinon');
const {func1} = require('./util');
const a = require('./A');
const chai = require("chai");
const expect = chai.expect;
describe('func1', () => {
it('should work', () => {
const stub = sinon.stub(a, 'func2').returns('everyone');
expect(func1()).to.be.equal('hello everyone'); // Success!
});
});
获取断言失败... Sinon stub func2 没有存根
AssertionError: 预期 'hello world' 等于 'hello 大家' 在上下文。 (测试\util.test.js:10:27) 在 processImmediate (internal/timers.js:456:21)
- 预期 - 实际
-“你好世界” +“大家好”
【问题讨论】:
-
func2 不能像那样被存根,因为 func1 已经需要原始的 func2 而不是你之后创建的存根,所以断言合理地失败了
-
那我就没有办法测试这个功能了吗?
-
因为它现在编码不,但是如果你使用 func2 作为依赖而不是按原样需要它,有一种方法,称为依赖注入
-
非常感谢..明白了..
标签: javascript unit-testing mocha.js sinon sinon-chai