以下为ChatGPT自动生成的解答,正确与否请自行判断。 也许你也可以从大家的发帖中找到想要的答案!
BFE.devAI解答 - JavaScript 代码题
38. 实现`jest.spyOn()`
实现思路可以分成几个步骤:
- 储存原来的 method
- 重写 method, 让它调用原 method, 然后在内部执行 spy。
- 返回 spy 对象,包含 calls 属性,以便之后验证。
代码实现如下:
function spyOn(obj, methodName) { const originalFn = obj[methodName] // 1. 储存原 method const calls = [] // 存储每一次调用时的参数 // 重写 method obj[methodName] = function(...args) { calls.push(args) // 存储一次调用所带的参数 return originalFn.apply(this, args) // 执行原来的 method,并返回其返回值 } // 返回 spy 对象 return { calls, // 如果你想要 mock 掉原来的 method, 可以用 restore 方法 restore() { obj[methodName] = originalFn } }}
在测试中应该这样使用:
const obj = { data: 1, increment(num) { this.data += num }}const spy = spyOn(obj, 'increment')obj.increment(1)console.log(obj.data) // 2obj.increment(2)console.log(obj.data) // 4console.log(spy.calls)
结果会和题目中的代码一样。