revert back to original function after mocking it Vitest

20 Views Asked by At

I need to restore the original functionality after mocking in the first test. Is it possible to do this without making a deep copy of @client and cleaning up the functions in a before each?

// users.spec.js
import { describe, test, expect, vi } from 'vitest'
import UsersAPI from '@/users.js'

vi.mock('@/client')

describe('Users API', () => {
  test('Users API.getUsers', async () => {
    1️⃣
    const client = await import('@/client')

    2️⃣
    const response = { data: [{ id: 1, name: 'john doe' }] }
    client.default.get = vi.fn().mockResolvedValue("hello")
    
    const users = await UsersAPI.getUsers()
    expect(client.default.get).toHaveBeenCalled()
    expect(client.default.get).toEqual("hello")
  })
  
  test("use original get", async () => {
    1️⃣
    const client = await import('@/client')

    2️⃣
    const response = { data: [{ id: 1, name: 'john doe' }] }
    client.default.get = vi.fn().mockResolvedValue("bye")
    expect(client.default.get).toEqual("bye") // it resolves to hello
  })
})

This works but it looks anti pattern. So my test files will get messy.

I've also tried a doUnmock inside each test and unDoMock in a beforeEach but it didn't work.

const clientHelper = await import("@/client")

const deepCopiedClient = deepCopy(clientHelper);

beforeEach(() => {
    cleanUp() // replaces the functionality with original
})
0

There are 0 best solutions below