tinyspy
minimal fork of nanospy, with more features 🕵🏻♂️
Usage
Warning! Does not support mocking ES Modules. You can use it with vitest
, who does additional transpormations, to mock ESM.
spy
Simplest usage would be:
const fn = (n: string) => n + '!'
const spied = spy(fn)
fn('a')
console.log(method.called)
console.log(method.callCount)
console.log(method.calls)
console.log(method.results)
console.log(method.returns)
You can reassign mocked function:
const fn = (n: string) => n + '!'
const spied = spy(fn).willCall((n) => n + '.')
fn('a')
console.log(method.returns)
You can reset calls, returns, called and callCount with reset
function and restore mock to it's original implementation with restore
method:
const fn = (n: string) => n + '!'
const spied = spy(fn).willCall((n) => n + '.')
fn('a')
console.log(method.called)
console.log(method.callCount)
console.log(method.calls)
console.log(method.returns)
fn.reset()
console.log(method.called)
console.log(method.callCount)
console.log(method.calls)
console.log(method.returns)
fn.restore()
console.log(fn('a')).toBe('a!')
console.log(method.callCount)
spyOn
All spy
methods are available on spyOn
.
You can spy on an object's method or setter/getter with spyOn
function.
let apples = 0
const obj = {
getApples: () => 13,
}
const spy = spyOn(obj, 'getApples', () => apples)
apples = 1
console.log(obj.getApples())
console.log(spy.called)
console.log(spy.returns)
let apples = 0
let fakedApples = 0
const obj = {
get apples() {
return apples
},
set apples(count) {
apples = count
},
}
const spyGetter = spyOn(obj, { getter: 'apples' }, () => fakedApples)
const spySetter = spyOn(obj, { setter: 'apples' }, (count) => {
fakedApples = count
})
obj.apples = 1
console.log(spySetter.called)
console.log(spySetter.calls)
console.log(obj.apples)
console.log(fakedApples)
console.log(apples)
console.log(spyGetter.called)
console.log(spyGetter.returns)
You can even make an attribute into a dynamic getter!
let apples = 0
const obj = {
apples: 13,
}
const spy = spyOn(obj, { getter: 'apples' }, () => apples)
apples = 1
console.log(obj.apples)
You can restore spied function to it's original value with restore
method:
let apples = 0
const obj = {
getApples: () => 13,
}
const spy = spyOn(obj, 'getApples', () => apples)
console.log(obj.getApples())
obj.restore()
console.log(obj.getApples())