How type mocks with vitest?
Asked Answered
G

3

7

I want to mock fs with vitest and I am successfully doing so, however I am using any to do so. Consider

import { promises as fs } from 'fs';

vi.mock('fs')

it('can mock', async () => {
  // Property 'mockResolvedValue' does not exist on type '{ ......
  fs.readdir.mockResolvedValue([])

  // ok but can we do better?
  (fs.readdir as any).mockResolvedValue([])
})

How can I improve the typing here?

Griselgriselda answered 17/5, 2023 at 15:48 Comment(1)
Vitest generally follows Jest's interface, does it have jestjs.io/docs/mock-function-api/#jestmockedsource-options? (Edit: yes.)Eph
G
10

As @jonrsharpe pointed to in the comment, we can use this syntax:

import { promises as fs } from 'fs';

vi.mock('fs')

it('can mock', async () => {
  vi.mocked(fs.readdir).mockResolvedValue([])
})
Griselgriselda answered 17/5, 2023 at 15:58 Comment(0)
W
4

I resolve this by follow way

import { vi } from 'vitest'
import axios from 'axios';

// mock library
vi.mock('axios')

// mock library methods
const mockedAxios = vi.mocked(axios, true)

You can see this in vitest DOCS https://vitest.dev/guide/mocking.html#mocking

Walt answered 14/9, 2023 at 19:14 Comment(0)
M
1

I've been using typeof which is what I think @jonrsharpe was pointing you towards. Something like:

import * as fs from 'fs';
const mockedFs = fs as Mocked<typeof fs>;
mockedFs.readdir.mockResolvedValue([]);
Mansour answered 23/5, 2023 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.