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

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

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

  1. import { promises as fs } from 'fs';
  2. vi.mock('fs')
  3. it('can mock', async () => {
  4. // Property 'mockResolvedValue' does not exist on type '{ ......
  5. fs.readdir.mockResolvedValue([])
  6. // ok but can we do better?
  7. (fs.readdir as any).mockResolvedValue([])
  8. })

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:

  1. import { promises as fs } from 'fs';
  2. vi.mock('fs')
  3. it('can mock', async () => {
  4. vi.mocked(fs.readdir).mockResolvedValue([])
  5. })

答案2

得分: 2

我通过以下方式解决了这个问题:

  1. import { vi } from 'vitest'
  2. import axios from 'axios';
  3. // 模拟库
  4. vi.mock('axios')
  5. // 模拟库方法
  6. const mockedAxios = vi.mocked(axios, true)

你可以在 vitest 文档中查看这个 https://vitest.dev/guide/mocking.html#mocking

英文:

I resolve this by follow way

  1. import { vi } from 'vitest'
  2. import axios from 'axios';
  3. // mock library
  4. vi.mock('axios')
  5. // mock library methods
  6. const mockedAxios = vi.mocked(axios, true)

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

答案3

得分: 1

我一直在使用 typeof,我认为 @jonrsharpe 指向的是这个。类似于以下代码:

  1. import * as fs from 'fs';
  2. const mockedFs = fs as Mocked<typeof fs>;
  3. mockedFs.readdir.mockResolvedValue([]);
英文:

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

  1. import * as fs from &#39;fs&#39;;
  2. const mockedFs = fs as Mocked&lt;typeof fs&gt;;
  3. 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:

确定