乐闻世界logo
搜索文章和话题

How to do manual mocks in Vitest?

1个答案

1

A common approach to implementing manual mocking in Vitest is by using the vi.fn() function to create a mock function or the vi.mock() method to mock an entire module. Below are specific steps and examples for implementing manual mocking.

Mock a Function

If you only need to mock a single function, you can use vi.fn() to create a mock function. For example, if you have a utils.js file and you want to mock the calculate function within it:

javascript
// utils.js export const calculate = () => { // Actual implementation... };

You can do this in your test file:

javascript
import { calculate } from './utils'; import { it, expect } from 'vitest'; // Create a mock function const mockCalculate = vi.fn(() => 42); // Replace the original function with the mock function calculate = mockCalculate; it('should use the mock function', () => { const result = calculate(); expect(result).toBe(42); expect(mockCalculate).toHaveBeenCalled(); });

Mock a Module

If you need to mock multiple functions or the entire module, you can use vi.mock(). For example, if you still want to mock the utils.js module:

javascript
// utils.js export const calculate = () => { // Actual implementation... }; export const anotherFunction = () => { // Implementation of another function... };

Your test file can be written as:

javascript
import { it, expect } from 'vitest'; import * as utils from './utils'; // Mock the entire utils module vi.mock('./utils', () => { return { calculate: vi.fn(() => 42), anotherFunction: vi.fn(() => 'mocked value'), }; }); it('should use the mock functions from the mocked module', () => { const result = utils.calculate(); const anotherResult = utils.anotherFunction(); expect(result).toBe(42); expect(anotherResult).toBe('mocked value'); expect(utils.calculate).toHaveBeenCalled(); expect(utils.anotherFunction).toHaveBeenCalled(); });

Note that when using vi.mock(), Vitest automatically applies it to all files that import the mocked module. This means that once you mock a module in one test file, all other tests that import this module will use the mocked version until you call vi.resetModules(). This is a powerful feature, but you need to be careful when using it to avoid unintended sharing of mock state between tests.

2024年6月29日 12:07 回复

你的答案