Beware of mock once

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the testing category.

Last Updated: 2024-04-26

I was using some code that mocked the first call of a method and then called the real thing on subsequent calls. I did this to give a fixed value to Date.now.

jest.spyOn(Date, "now").mockImplementationOnce(() => new Date("2019-09-1"))

Later on, I found that these tests were failing. This was because there were now multiple calls to Date.now in the underlying code and they were giving different answers. My single mock response had been used up and the real date was showing elsewhere.

Lesson

Be careful with mockImplementationOnce. It seems like a good idea for surgical mocking. But in reality, it causes brittle tests as the stack gets larger and you accidentally introduce more code that calls the same function.