spyOn is not working
Describe the bug
I call spyOn on an imported module, but when I run the test, the actual implementation is passed to my testing module.
Reproduction
//Test file
import * as database from '../../database'
import * as useDateHook from '../useDate'
import * as useStorageHook from '../useStorage'
import { useGameStatusStorage } from '.'
const getStorageMock = vi.fn()
const setStorageMock = vi.fn()
const getTodayMock = vi.fn()
const isSameDateMock = vi.fn()
const getDailyWordMock = vi.fn()
describe('useGameStatusStorage', () => {
afterEach(() => vi.clearAllMocks())
vi.spyOn(useStorageHook, 'useStorage').mockReturnValue({
getStorage: getStorageMock,
setStorage: setStorageMock,
})
vi.spyOn(useDateHook, 'useDate').mockReturnValue({
getToday: getTodayMock,
isSameDate: isSameDateMock,
})
vi.spyOn(database, 'getDailyWordFromDatabase').mockImplementation(
getDailyWordMock
)
it('Should call getStorage and setStorage with correct params when refreshGame is called', async () => {
const todayMock = 'TODAY-MOCK'
const dailyWordMock = 'DAILY-WORD-MOCKs'
getTodayMock.mockReturnValue(todayMock)
getDailyWordMock.mockReturnValue(dailyWordMock)
useGameStatusStorage().refreshGame()
expect(getStorageMock).toHaveBeenCalledTimes(1)
expect(setStorageMock).toHaveBeenCalledTimes(1)
expect(setStorageMock).toHaveBeenCalledWith({
guesses: [],
gameFinishStatus: null,
lastDate: todayMock,
dailyWord: dailyWordMock,
})
})
})
// useGameStatusStorage file
import { getDailyWordFromDatabase } from '../../database'
import { useDate } from '../useDate'
import { useStorage } from '../useStorage'
const { getToday } = useDate()
const today = getToday()
const defaultGuessStatistics: number[] = Array(GUESSES_AMOUNT).fill(0)
const defaultGameStatusStorage: GameStatusStorage = {
bestStreak: 0,
guesses: [],
guessStatistics: defaultGuessStatistics,
totalGamesAmount: 0,
winPercentage: 0,
winStreak: 0,
gameFinishStatus: null,
winAmount: 0,
lossAmount: 0,
lastDate: today,
dailyWord: getDailyWordFromDatabase(today),
}
export const useGameStatusStorage: () => UseGameStatusStorageHook = () => {
const { getStorage, setStorage } = useStorage<GameStatusStorage>( defaultGameStatusStorage)
const refreshGame = () => {
const storage = getStorage()
setStorage({
...storage,
guesses: [],
gameFinishStatus: null,
lastDate: today,
dailyWord: getDailyWordFromDatabase(today),
})
}
return {
refreshGame,
}
}
When I run this test it returns
FAIL src/hooks/useGameStatusStorage/useGameStatusStorage.test.ts > useGameStatusStorage > Should call getStorage and setStorage with correct params when refreshGame is called
AssertionError: expected "spy" to be called with arguments: [ { guesses: [], …(3) } ]
Received:
1st spy call:
Array [
Object {
"dailyWord": "DAILY-WORD-MOCKs",
"gameFinishStatus": null,
"guesses": Array [],
- "lastDate": "TODAY-MOCK",
+ "lastDate": "2023-07-03",
},
]
'2023-07-03' is the actual implementation return from useDate().getToday() module, i've used debugger and checked that getToday have been called before spy (I've tried to use vi.mock but it didnt worked as well)
System Info
System:
OS: Linux 5.10 Ubuntu 20.04.6 LTS (Focal Fossa)
CPU: (12) x64 AMD Ryzen 5 5600X 6-Core Processor
Memory: 8.48 GB / 11.64 GB
Container: Yes
Shell: 5.8 - /usr/bin/zsh
Binaries:
Node: 20.2.0 - ~/.asdf/installs/nodejs/20.2.0/bin/node
Yarn: 1.22.19 - ~/.asdf/installs/nodejs/20.2.0/bin/yarn
npm: 9.6.7 - ~/.asdf/plugins/nodejs/shims/npm
npmPackages:
@vitejs/plugin-react: ^4.0.0 => 4.0.0
@vitest/coverage-v8: ^0.32.0 => 0.32.0
@vitest/ui: ^0.32.0 => 0.32.0
vite: ^4.3.9 => 4.3.9
vitest: ^0.32.4 => 0.32.4
Used Package Manager
npm
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guidelines.
- [X] Read the docs.
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [X] Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- [X] The provided reproduction is a minimal reproducible example of the bug.
Hello @lerockit. Please provide a minimal reproduction using a GitHub repository or StackBlitz. Issues marked with need reproduction will be closed if they have no activity within 3 days.
I cannot run tests with this reproduction because it doesn't expose other files. Please create a minimal reproduction
Sorry, here is a link with exact same error I'm getting
https://stackblitz.com/edit/vitest-dev-vitest-3r9tmb?file=test%2FuseGameStatusStorage.test.ts
I believe this may be related: https://stackoverflow.com/questions/76284919/vitest-vi-spyon-does-not-work-on-side-effects
If it helps, this is a simple reproduction from that SO post: https://github.com/nxho/vitest-spyon-repro
Here is a workaround for this issue using the SO post example: https://stackoverflow.com/a/76872947/2425556
If it helps, this is a simple reproduction from that SO post: nxho/vitest-spyon-repro
This is not a bug. This is how JavaScript works, you cannot intercept declared function. Try to spy on a function without any exports here:
function test() {
return 'original'
}
function call() {
return test()
}
// your code to change the result of test when calling "call"
When you are using vi.spyOn or vi.mock you mock outside of the module usage, because it's exported.
Can you please see https://gist.github.com/sureshvv/3c9825040be95692ae50181f537c9b39
Is this a correct example?
Test fails:
AssertionError: expected "sub1" to be called 1 times, but got 0 times