我试着自己写一个测试间谍。只是为了更熟悉这个话题。
下面是代码:
// --------- SPY - Start -----------------------------------
class Spy {
constructor(func) {
this.func = func;
this.returnValue = null;
this.result = null;
this.countFuncCalled = 0;
}
invoke(...givenArgs) {
this.receivedArgs = givenArgs;
this.returnValue = this.func(...givenArgs);
this.countFuncCalled++;
}
}
// --------- SPY - End ------------------------------------
const calc = {
add: (a, b) => {
return a + b;
},
sub: (a, b) => {
return a - b;
}
}
const addSpy = new Spy(calc.sub);
addSpy.invoke(9, 4);
console.log(`Used arguments: ${addSpy.receivedArgs.join(", ")}`);
console.log(`Return value: ${addSpy.returnValue}`);
console.log(`Count of function-calls: ${addSpy.countFuncCalled}`);
addSpy.invoke(8, 7);
console.log(`Used arguments: ${addSpy.receivedArgs.join(", ")}`);
console.log(`Return value: ${addSpy.returnValue}`);
console.log(`Count of function-calls: ${addSpy.countFuncCalled}`);你对我的实现有什么看法?这样做基本上是正确的吗?
我在使用ES6-特征(类,休息,传播),对吗?
你会有什么不同的做法,为什么?
期待着阅读你的评论和答案。
https://codereview.stackexchange.com/questions/206188
复制相似问题