• Skip to main content
  • Home
  • Blog
  • About
  • Github
  • Contact

Courtney Sims

unit tests

Mocking Functions from Third Parties with Vitest

May 30, 2025 by courtneysims Leave a Comment

I needed to mock mime.getType() recently for a unit test and struggled to figure out how to mock it with just a quick google, so I’m documenting it myself.

Problem

Mime is an npm package for interacting with file formatting types. In my particular use case, I wrote a function that read a file and then executed different logic depending on the type of that file. The code looked vaguely similar to the following oversimplification:


  function do_Something(filePath: string) {
	const mimeType = mime.getType(path)

	if (mimeType === 'image/gif') {
		return 'something!'
	} else {
                return 'something else!'
        }
  }

I wanted to test that the correct value was returned for both gifs and non-gifs, but for the sake of a true unit test, I didn’t want to create actual gif and non-gif files in my test suite. I wanted to pass in any random strings as file paths and have one test pretend mime.getType() returned “image/gif” while another pretended it returned something else.

Solution

Mock mime with vi.mock(), using a factory function to mock getType() with vi.fn(). Anything you can do with vi.fn(), you can now do with getType()!


  vi.mock('mime', () => {
       return {
	    default: {
		getType: vi.fn(),
	    },
       }
  })

  # Restore the mock after each test so that previous test results don't 
  # influence future test results
  afterEach(async () => {
	vi.restoreAllMocks()
  })

  ...

  describe('do_Something', async () => {
	it("returns 'something!' for gifs", async () => {
            # Since getType is mocked with vi.fn(), you can use 
            # mockReturnValueOnce()
	    vi.mocked(mime.getType).mockReturnValueOnce('theType')
	    const actual = await get_mime_type('notARealFile.gif')
	    expect(actual).toEqual('something!')
	})
	it("returns 'something else!" for non-gifs", async () => {
	    vi.mocked(mime.getType).mockReturnValueOnce('inode/directory')
	    const actual = await get_mime_type('notARealFile.pdf')
	    expect(actual).toEqual('something else!')
	})
    })

Other notes

  1. I used vi.mocked() within the code of the actual tests to satisfy Typescript’s typing desires.
  2. It’s a good idea to put vi.mock() at the top of your test file. You don’t have to. You can put it anywhere in the file, but not putting it at the top communicates some expectations inadvertently that won’t be met. vi.mock() is hoisted and called before even the other imports in the file. Putting it at the top sets the right behavioral expectations for future contributors (and perhaps future you).

Filed Under: Code Tagged With: javascript, typescript, unit tests, vitest

Copyright © 2025 · Lifestyle Pro on Genesis Framework · WordPress · Log in