例如,我有两个功能:
function functionOne() {
var a = 1;
var b = 2;
var sum = a + b;
return sum;
}
function functionTwo() {
var receivedSum = functionOne();
console.log('just do something with ' + receivedSum);
}
我想测试功能Two,并且需要以某种方式获取receivedSum的值。 可能吗? Sinon.js或其他一些库对我有帮助吗?
答案 0 :(得分:0)
最佳实践是黑匣子测试,但是 可以将内部函数包装在间谍程序中,并使用spy.returnValues
检查它返回的值:
lib.js
export const libFunc = () => 'the value';
code.js
import { libFunc } from './lib';
export const func = () => {
// ...do stuff...
const value = libFunc();
// ...do more stuff...
}
code.test.js
import * as sinon from 'sinon';
import * as lib from './lib';
import { func } from './code';
test('func', () => {
const spy = sinon.spy(lib, 'libFunc'); // spy on libFunc
func(); // call func which calls libFunc
expect(spy.returnValues[0]).toBe('the value'); // SUCCESS
});