Open utterances-bot opened 2 years ago
Thank you again for writing this up. This and the first article is a life-saver for someone who got mocks to work but never quite understood when to use which method of mocking.
I went through your article in great detail and wanted to share some issues I ran in to, in case it can help the next person reading your article:
getSillyWalk
method is a bit harder to grok than just returning a Math.random()
getSillyWalk(numberOfSteps) {
const steps = []
for (let i = 0; i < numberOfSteps; i++) {
if (steps[steps.length - 1] !== 'left') {
steps.push('left')
} else {
steps.push('right')
}
}
// shuffle
return steps.sort(() => 0.5 - Math.random())
it('gets the real meaning of life', () => {
jest.dontMock('./monty-python')
const RealMontyPython = require('./monty-python')
// ... [filling out this part that was omitted for brevity; not sure if it's what was intended or not]
const mathRandomSpy = jest.spyOn(Math, 'random')
mathRandomSpy.mockImplementation(() => '¯\_(ツ)_/¯')
const montyPython = new RealMontyPython()
expect(montyPython.getTheMeaningOfLife()).toBe('¯\_(ツ)_/¯')
mathRandomSpy.mockRestore()
jest.resetModules()
})
Also, your explanation of how mocks are hoisted
was super helpful. I ran into that error and conflated it with a bunch of other things. Your explanation clarified everything up.
Thank you again for writing all of this out so simply and succinctly. 🙏
Thank you so much for you generous feedback! I updated my posts based on what you said 🚀 hopefully I covered everything that you had trouble with, and I'm so happy my posts helped you understand these features!
Mocking with Jest: Taking Advantage of the Module System
Using Jest to reimplement certain modules when you don't want their usual behavior during testing.
https://silvenon.com/blog/mocking-with-jest/modules/