(options: MockInstanceOption = {})
| 28 | const MOCK_CONFIGS = new WeakMap<Mock<Procedure | Constructable>, MockConfig>() |
| 29 | |
| 30 | export function createMockInstance(options: MockInstanceOption = {}): Mock<Procedure | Constructable> { |
| 31 | const { |
| 32 | originalImplementation, |
| 33 | restore, |
| 34 | mockImplementation, |
| 35 | resetToMockImplementation, |
| 36 | resetToMockName, |
| 37 | } = options |
| 38 | |
| 39 | if (restore) { |
| 40 | MOCK_RESTORE.add(restore) |
| 41 | } |
| 42 | |
| 43 | const config = getDefaultConfig(originalImplementation) |
| 44 | const state = getDefaultState() |
| 45 | |
| 46 | const mock = createMock({ |
| 47 | config, |
| 48 | state, |
| 49 | ...options, |
| 50 | }) |
| 51 | const mockLength = (mockImplementation || originalImplementation)?.length ?? 0 |
| 52 | Object.defineProperty(mock, 'length', { |
| 53 | writable: true, |
| 54 | enumerable: false, |
| 55 | value: mockLength, |
| 56 | configurable: true, |
| 57 | }) |
| 58 | // inherit the default name so it appears in snapshots and logs |
| 59 | // this is used by `vi.spyOn()` for better debugging. |
| 60 | // when `vi.fn()` is called, we just use the default string |
| 61 | if (resetToMockName) { |
| 62 | config.mockName = mock.name || 'vi.fn()' |
| 63 | } |
| 64 | MOCK_CONFIGS.set(mock, config) |
| 65 | REGISTERED_MOCKS.add(mock) |
| 66 | |
| 67 | mock._isMockFunction = true |
| 68 | mock.getMockImplementation = () => { |
| 69 | // Jest only returns `config.mockImplementation` here, |
| 70 | // but we think it makes sense to return what the next function will be called |
| 71 | return config.onceMockImplementations[0] || config.mockImplementation |
| 72 | } |
| 73 | |
| 74 | Object.defineProperty(mock, 'mock', { |
| 75 | configurable: false, |
| 76 | enumerable: true, |
| 77 | writable: false, |
| 78 | value: state, |
| 79 | }) |
| 80 | |
| 81 | mock.mockImplementation = function mockImplementation(implementation) { |
| 82 | config.mockImplementation = implementation |
| 83 | return mock |
| 84 | } |
| 85 | |
| 86 | mock.mockImplementationOnce = function mockImplementationOnce(implementation) { |
| 87 | config.onceMockImplementations.push(implementation) |
no test coverage detected