Isn't using spied reference better than original function in thumb-war.3.todo.js
kvedantmahajan opened this issue · 3 comments
I will just post my solution
import thumbWar from '../thumb-war'
import * as utils from '../utils'
test('returns winner', () => {
const spy = jest.spyOn(utils, 'getWinner').mockImplementation((p1, p2) => p2)
const winner = thumbWar('Kent', 'Kushal')
expect(winner).toBe('Kushal')
expect(spy).toHaveBeenCalledTimes(2)
spy.mock.calls.forEach(args => {
expect(args).toEqual(['Kent', 'Kushal'])
})
spy.mockRestore()
})
Now in your solution you have used reference to original utils.getWinner
while calling mockImplementation
. But I just read from docs and feel that using a reference to spy function i.e. jest.spyOn(object, 'methodName')
would be a right handle to call further methods on it from jest.
So, as you can see I called mockImplementation
on same and then used expect(spy)
instead of expect(utils.getWinner)
.
I just want to know the difference it would create with your approach by referencing original function instead of spied
one. Same uses continues in my code snippet i.e. spy.mock.calls
and spy.mockRestore
as the tests are passing in either case
Hi @kushalmahajan,
It's exactly the same thing
const spy = jest.spyOn(utils, 'getWinner').mockImplementation((p1, p2) => p2)
console.log(spy === utils.getWinner) // true
So feel free to do whichever you want.
Umm...I was thinking along the lines of mock which I guess uses different reference/memory address for a function. And is a better choice than spy to NOT modify the original function. Hope, I'm thinking correctly!
Hmm... I'm not sure I understand what you mean. The example code you have above is basically identical to the solution. What do you think the difference is?