如何使用 vitest 进行类型模拟?

huangapple go评论68阅读模式
英文:

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 &#39;fs&#39;;
const mockedFs = fs as Mocked&lt;typeof fs&gt;;
mockedFs.readdir.mockResolvedValue([]);

huangapple
  • 本文由 发表于 2023年5月17日 23:48:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定