Module Mocking
Harness provides powerful module mocking capabilities that allow you to replace entire modules or parts of modules with mock implementations. This is particularly useful for testing React Native code that depends on native modules or third-party libraries.
mock()
Mock a module by providing a factory function that returns the mock implementation.
requireActual()
Get the actual (unmocked) implementation of a module. This is useful for partial mocking where you want to preserve some exports while replacing others.
unmock()
Remove a mock for a specific module, restoring it to its original implementation.
resetModules()
Clear all module mocks and the module cache. This is useful in afterEach hooks to ensure tests don't interfere with each other.
Best Practices
-
Always reset modules in
afterEach: UseresetModules()in your test cleanup to prevent mocks from leaking between tests. -
Use
requireActualfor partial mocks: When you only need to mock specific exports, userequireActual()to preserve the rest of the module. -
Factory functions are called lazily: The factory function is only called when the module is first required, not when
mock()is called. -
Module caching: Modules are cached after first require. Use
resetModules()if you need to reinitialize a mocked module.
API Reference
mock(moduleId: string, factory: () => unknown): void- Mock a module with a factory functionunmock(moduleId: string): void- Remove a mock for a specific modulerequireActual<T = any>(moduleId: string): T- Get the actual (unmocked) implementation of a moduleresetModules(): void- Clear all module mocks and the module cache
