英文:
How type mocks with vitest?
问题
如何改进此处的类型定义?
英文:
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?
答案1
得分: 3
import { promises as fs } from 'fs';
vi.mock('fs')
it('can mock', async () => {
vi.mocked(fs.readdir).mockResolvedValue([])
})
英文:
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([])
})
答案2
得分: 2
我通过以下方式解决了这个问题:
import { vi } from 'vitest'
import axios from 'axios';
// 模拟库
vi.mock('axios')
// 模拟库方法
const mockedAxios = vi.mocked(axios, true)
你可以在 vitest 文档中查看这个 https://vitest.dev/guide/mocking.html#mocking
英文:
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
答案3
得分: 1
我一直在使用 typeof
,我认为 @jonrsharpe 指向的是这个。类似于以下代码:
import * as fs from 'fs';
const mockedFs = fs as Mocked<typeof fs>;
mockedFs.readdir.mockResolvedValue([]);
英文:
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([]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论