### Manual Mocking Example Source: https://github.com/hmil/omnimock/blob/master/README.md Demonstrates the verbose and maintenance-heavy approach of manually defining mock objects for unit tests. ```ts const fakeCard: MtgCard = { cost: 'UW', color: 'white', kind: 'sorcery', art: 'John Avon', play: () => ({} as any), burry: () => ({} as any), // ... } const gameState: MtgState = { player1: { getManaPool() { return [ { color: 'W', qty: 1 } ]; }, // ... }, player2: { getManaPool() { return [ ]; // Not important }, // ... }, clock: { player: 1, phase: 'precombat main' } } const result = battlefield.castSpell(gameState, fakeCard); expect(result.type).toBe('illegal move'); expect(result.reason).toBe('not enough mana'); ``` -------------------------------- ### Match by type with anyNumber Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches any variable of a specific type. This example demonstrates anyNumber. ```ts const mockFn = mock<(n?: number | string): string>(); when(mockFn(anyNumber())).return('OK'); instance(mockFn)(123); // 'OK' instance(mockFn)('hello'); // 'OK' instance(mockFn)(); // Error ``` -------------------------------- ### Create and configure a mock Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide Demonstrates the basic workflow of creating a mock, defining return values for specific arguments, and generating an instance. ```ts interface FoodPlant { process(ingredient: 'potato' | 'tomato'): number; } import { mock, instance, when } from 'omnimock'; // Step 1: Create a mock const plantMock = mock('plantMock'); // Step 2: Define behaviors when(plantMock.process('potato')).return(2); // Step 3: Use your mock const foodPlant = instance(plantMock); foodPlant.process('potato') === 2; // true foodPlant.process('tomato'); // Error: No behavior defined for .process('tomato') ``` -------------------------------- ### Use mockInstance shortcut Source: https://github.com/hmil/omnimock/blob/master/README.md A more concise syntax for creating mock instances. ```ts const mockCard = mockInstance('fake card', { id: 1038, color: 'white' }); when(codex.getCard('Starlight')).return(mockCard); ``` -------------------------------- ### Using mockInstance for data objects Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide Provides a shorthand for creating mock instances with predefined properties, ideal for DTOs. ```ts interface Vegetable { type: string; edible: boolean; } import { mockInstance } from 'omnimock'; const edibleMock = mockInstance('edibleMock', { edible: true }); expect(edibleMock.edible).toBe(true); ``` -------------------------------- ### Create a partial mock with instance Source: https://github.com/hmil/omnimock/blob/master/README.md Use instance and mock to define only necessary properties, throwing errors if missing properties are accessed. ```ts const mockCard = instance(mock('fake card', { // Omit the properties you don't need. // Omnimock will throw an error if it turns out you need them. id: 1038, color: 'white' })); when(codex.getCard('Starlight')).return(mockCard); ``` -------------------------------- ### anything() Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches any argument, but not omitted arguments. ```APIDOC ## anything() ### Description Matches any argument, but not omitted arguments. ### Usage `anything()` ``` -------------------------------- ### Create a mock and set expectations Source: https://github.com/hmil/omnimock/blob/master/README.md Use the mock() method to define expectations and pass the instance to the tested code. ```ts // Use the mock to set expectations const someServiceMock = mock(SomeService); when(someServiceMock.doStuff()).return('hi').once(); // Pass the instance to the class you are testing const someService = instance(myMock); const testClass = new TestClass(someService); ``` -------------------------------- ### Combine expectations on the same path Source: https://github.com/hmil/omnimock/blob/master/README.md Shows how multiple expectations on the same path are combined and the importance of declaration order. ```ts // These expectations are combined naturally when(myMock.members.getByName('Steve').job.getCompany().name).useValue('Pixar'); when(myMock.members.getByName('Steve').job.getCompany().address).useValue('1200 Park Ave'); when(myMock.members.getByName('Steve').job.title).useValue('Engineer'); // This is added after to catch any member who is not Steve when(myMock.members.getByName(anyString())).return(defaultMember); // Pitfall: despite being added after the catch-all, this is combined with the other 'Steve' expectations. // Because `getByName('Steve')` was specified before `getByName(anyString())`, this is actually reachable. // If you remove all three `Steve` expectations above, then this expectation becomes unreachable. when(myMock.members.getByName('Steve').job.ranking).useValue(12); instance(myMock).members.getByName('Steve').job.getCompany().name // 'Pixar' instance(myMock).members.getByName('Steve').address // Error: Unexpected member access instance(myMock).members.getByName('John').address // default address instance(myMock).members.getByName('Steve').job // {} instance(myMock).members.getByName('Steve').job.ranking // 12 ``` -------------------------------- ### Create backed mocks Source: https://github.com/hmil/omnimock/blob/master/README.md Create a mock backed by an actual object instance to support call-through features. ```ts const realAssemblyService = { assemble(parts: PartsList, blueprint: Blueprint) { /* ... */ } version: 2 }; // realAssemblyService "backs" assemblyServiceMock const assemblyServiceMock = mock('assemblyServiceMock', realAssemblyService); // This works well with classes too const assemblyServiceMock = mock('assemblyServiceMock', new AssemblyService()); ``` ```ts when(assemblyServiceMock.assemble).useActual().never(); ``` -------------------------------- ### Enable instanceof support Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide Use the constructor shorthand syntax to ensure instanceof checks function correctly with mocked objects. ```ts const edibleMock = mock('edibleMock', { edible: true }); instance(edibleMock) instanceof Vegetable // false const edibleMock = mock(Vegetable, { edible: true }); instance(edibleMock) instanceof Vegetable // true ``` -------------------------------- ### Create function mocks Source: https://github.com/hmil/omnimock/blob/master/README.md Mock simple functions as either virtual or backed mocks. ```ts // Named virtual mock const luckyNumberMock = mock<(name: string) => number>('luckyNumber'); // Backed mock const luckyNumberMock = mock('luckyNumber', (name: string) => { return name.charCodeAt(0); }); ``` -------------------------------- ### Return mock instances with unknown usage Source: https://github.com/hmil/omnimock/blob/master/README.md Provide a mock instance without initial attributes, optionally using a constructor for better accuracy. ```ts when(codex.getCard('Starlight')).return(mockInstance('fake card')); // Or better, if you have access to a constructor this is more accurate: when(codex.getCard('Starlight')).return(mockInstance(MtgCard)); ``` -------------------------------- ### Match any argument with anything Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches any provided argument, but fails if the argument is omitted. ```ts const mockAnything = mock<(n?: number): string>(); when(mockAnything(anything())).return('OK'); instance(mockAnything)(123); // 'OK' instance(mockAnything)(); // Error ``` -------------------------------- ### Use deep chaining for mock configuration Source: https://github.com/hmil/omnimock/blob/master/README.md An alternative to callbacks for configuring mock behavior using deep chaining. ```ts when(codex.getCard('Starlight').play(anything())).call(gameState => { expect(gameState.turn).toBe(2); }); ``` -------------------------------- ### Create a standard mock object Source: https://github.com/hmil/omnimock/blob/master/README.md Define a mock object manually and return it using the when/return pattern. ```ts const mockCard: MtgCard = { id: 1038, cost: 'UW', color: 'white', kind: 'sorcery', art: 'John Avon', // ... }; when(codex.getCard('Starlight')) .return(mockCard); ``` -------------------------------- ### Handle nested property resolution errors Source: https://github.com/hmil/omnimock/blob/master/README.md Demonstrates how matcher resolution works left-to-right and the potential for errors when expectations conflict. ```ts when(myMock.members.getByName('Steve').job.getCompany().name).useValue('Pixar'); when(myMock.members.getByName(anyString()).job.getCompany().address).useValue('1200 Park Ave'); // Throws an error because, the first expectation won at 'getByName' // and it does not expect an access to 'address'. // If you removed the first line, then this would return '1200 Park Ave' instance(myMock).members.getByName('Steve').job.getCompany().address ``` -------------------------------- ### Match with logical OR using anyOf Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches if the variable matches any of the provided arguments. ```ts const mockFn = mock<(n?: number | string): string>(); when(mockFn(anyOf(12, 'hello'))).return('OK'); instance(mockFn)(12); // 'OK' instance(mockFn)('hello'); // 'OK' instance(mockFn)(42); // Error ``` -------------------------------- ### same(value) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches variables by strict equality (===). ```APIDOC ## same(value) ### Description Matches variables by strict equality (===). ### Usage `same(value)` ``` -------------------------------- ### instanceOf(type) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches an object which is an instanceof the expected type. ```APIDOC ## instanceOf(type) ### Description Matches an object which is an instanceof the expected type. ### Usage `instanceOf(type)` ``` -------------------------------- ### matching(predicate) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Lets you specify an arbitrary matching condition. ```APIDOC ## matching(predicate) ### Description This matcher lets you specify an arbitrary matching condition. Use this if you cannot find a built-in matcher that suits your needs. ### Usage `matching(value => boolean)` ``` -------------------------------- ### Match with logical AND using allOf Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches if the variable satisfies all provided matchers. ```ts class Cat { constructor(public readonly name: string) { } } const mockFn = mock<(n?: Cat): string>(); when(mockFn(allOf( instanceof(Cat), { name: 'Olinka' }))) .return('OK'); instance(mockFn)(new Cat('Olinka')); // 'OK' instance(mockFn)({ name: 'Olinka' }); // Error instance(mockFn)(new Cat('Oggies')); // Error ``` -------------------------------- ### Automatic Mocking with OmniMock Source: https://github.com/hmil/omnimock/blob/master/README.md Shows how to use OmniMock to define only the necessary properties and behaviors for a test case, improving readability and type safety. ```ts const fakeCard = mock('fakeCard', { cost: 'UW' }); const gameState = mock('gameState', { clock: { player: 1, phase: 'precombat main' } }); when(gameState.player1.getManaPool()) .return([ { color: 'W', qty: 1 } ]) .once(); const result = battlefield.castSpell(instance(gameState), instance(fakeCard)); expect(result.type).toBe('illegal move'); expect(result.reason).toBe('not enough mana'); ``` -------------------------------- ### allOf(...matchers) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches variables which match all of the provided arguments (logical AND). ```APIDOC ## allOf(...matchers) ### Description Matches variables which match all of the provided arguments. This is effectively a logical "AND" operation for matchers. ### Usage `allOf(matcher1, matcher2, ...)` ``` -------------------------------- ### anyOf(...matchers) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches variables which match any of the provided arguments (logical OR). ```APIDOC ## anyOf(...matchers) ### Description Matches variables which match any of the provided arguments. This is effectively a logical "OR" operation for matchers. ### Usage `anyOf(matcher1, matcher2, ...)` ``` -------------------------------- ### Handling promises Source: https://github.com/hmil/omnimock/blob/master/README.md Use helper methods to resolve or reject promises returned by mock methods. ```ts when(myMock.fetchRemoteData(1)).resolve('the data'); when(myMock.fetchRemoteData(0)).rejet('Invalid id'); ``` -------------------------------- ### Using argument matchers Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide Utilizes matchers like anyOf to define behaviors for multiple input values simultaneously. ```ts import { anyOf } from 'omnimock'; when(plantMock.process(anyOf('potato', 'tomato'))).return(4); foodPlant.process('tomato') === foodPlant.process('potato'); // true ( === 4) ``` -------------------------------- ### between(min, max) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches any variable between min and max (inclusive by default). ```APIDOC ## between(min, max) ### Description Matches any variable between min and max. Both min and max are inclusive by default, but can be made exclusive by passing `{ value: x, exclusive: true }`. ``` -------------------------------- ### Create partial mocks Source: https://github.com/hmil/omnimock/blob/master/README.md Omit properties when creating a backed mock to define only specific members. ```ts const assemblyServiceMock = mock('assemblyServiceMock', { version: 2 }); ``` ```ts const assemblyServiceMock = mock(AssemblyService, { version: 2 }); ``` ```ts assemblyService.version; // 2 assemblyService.assemble(parts, blueprint); // Error: unexpected property access: AssemblyService.assemble ``` -------------------------------- ### Create virtual mocks Source: https://github.com/hmil/omnimock/blob/master/README.md Mock interfaces or classes without providing an actual instance. ```ts // Mock an interface by passing it as a type argument to the mock function. // Give it a name to help print nice error messages const mockAssemblyService = mock('mockAssemblyService'); // Mock a class from its constructor. The name and type are infered automatically. const mockAssemblyService = mock(AssemblyService); ``` -------------------------------- ### Mocking templated functions Source: https://github.com/hmil/omnimock/wiki/Comparison-of-TypeScript-mocking-frameworks Demonstrates how a mocking framework should preserve type safety for functions with type arguments. ```ts interface MyVault { getSecretRecipe(s: T): T extends '5cr37' ? string : number; } const mock = createMock(); mock.getSecretReceipe('aaa'); // number // Some frameworks may think the return value here is `number`, which is wrong. mock.getSecretReceipe('5cr37'); // string ``` -------------------------------- ### Expect method or function calls Source: https://github.com/hmil/omnimock/blob/master/README.md Sets return values for mocked methods or simple functions. ```ts when(myMock.doStuff()).return('hi'); ``` ```ts when(myMock()).return('hi'); ``` -------------------------------- ### Mocking return values and properties Source: https://github.com/hmil/omnimock/blob/master/README.md Define static return values for methods or property access on a mock instance. ```ts // Mock the return value of a method when(myMock.sayMyName()).return('Heisenberg'); // Mock the value of a property or getter when(myMock.name).useValue('Heisenbug'); instance(myMock).sayMyName(); // Heisenberg instance(myMock).name; // Heisenbug ``` -------------------------------- ### Using fakes for custom logic Source: https://github.com/hmil/omnimock/blob/master/README.md Execute custom test code when a method is called, or replace a method with a custom function. ```ts when(myMock.divide(anyNumber(), 0)).callFake((a, b) => { expect(a).toBe(42); }); ``` ```ts when(myMock.doSomething()).callFake(() => 'something was done'); // Is equivalent to: when(myMock.doSomething).useValue(() => 'something was done'); ``` -------------------------------- ### Mocking nested objects with mockInstance Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide Demonstrates how to mock complex objects with nested structures using recursive mockInstance calls. ```ts interface Vitamin { letter: string; } interface Vegetable { // ... vitamins: Array; } const ascorbic = mockInstance('ascorbic', { edible: true, vitamins: [ mockInstance('vitamin', { letter: 'c' }) ] }); ``` -------------------------------- ### arrayEq(array) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches an array which has the same number of elements as the expected array and whose elements match those in the expected array. ```APIDOC ## arrayEq(array) ### Description Matches an array which has the same number of elements as the expected array and whose elements match those in the expected array. The expected array can contain nested matchers. ``` -------------------------------- ### Match variables with weakEquals Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Uses weak equality (==) to match variables. ```ts match(weakEquals(0), ''); // match ``` -------------------------------- ### Debug OmniMock expectations Source: https://github.com/hmil/omnimock/blob/master/README.md Use the debug utility to print all expectations currently registered on a mock instance. ```ts import { debug } from 'omnimock'; console.log(debug(myMock)); ``` -------------------------------- ### Match variables with same Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Uses strict equality (===) to match variables. ```ts const cat = { fur: 'fluffy' }; match(same(cat), { fur: 'fluffy' }); // no match match(same(cat), cat); // match const primitive = 2; match(same(primitive), 2); // match ``` -------------------------------- ### objectEq(object) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches an object by performing a recursive match against each member. ```APIDOC ## objectEq(object) ### Description Matches an object by performing a recursive match against each member. The set of members of the expected object must be the same as those of the actual object. ``` -------------------------------- ### Create custom matchers with matching Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Allows defining an arbitrary condition for matching. ```ts when(myMock(matching(value => value.charAt(2) === 'o'))).return(true); ``` -------------------------------- ### Delegating to real objects Source: https://github.com/hmil/omnimock/blob/master/README.md Delegate method calls and member access to the backing instance of a mock. ```ts const myMock = mock('myMock', { sayHello: (name: string) => `Hello ${name}!`, name: 'Willy' }); when(myMock.sayHello()).callThrough(); when(myMock.name).useActual(); instance(myMock).sayHello('beautiful'); // "Hello beautiful!" instance(myMock).name; // "Willy" ``` -------------------------------- ### jsonEq(value) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches an object whose JSON representation is the same as that of the expected. ```APIDOC ## jsonEq(value) ### Description Matches an object whose JSON representation is the same as that of the expected. ``` -------------------------------- ### Use mock factory shorthand Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide Pass a class directly to mock or mockInstance to infer type and name. This does not support abstract classes or interfaces. ```ts // The regular usage: Specify the type and the name of the mock const edibleMock = mockInstance('edibleMock', { edible: true }); // Shorthand: the type and name of the mock are inferred. const edibleMock = mockInstance(Vegetable, { edible: true }); // Works with `mock` too const edibleMock = mock(Vegetable); ``` ```ts const ascorbic = mockInstance(Vegetable, { edible: true, vitamins: [ mockInstance(Vitamin, { letter: 'c' }) ] }); ``` -------------------------------- ### Customize mock with a callback Source: https://github.com/hmil/omnimock/blob/master/README.md Use a callback to configure the mock builder directly, useful for complex mock behavior. ```ts when(codex.getCard('Starlight')) .return(mockInstance('fake card', {}, fakeCard => { when(fakeCard.play(anything())).call(gameState => { expect(gameState.turn).toBe(2); }); })); ``` -------------------------------- ### weakEquals(value) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches variables by weak equality (==). ```APIDOC ## weakEquals(value) ### Description Matches variables by weak equality (==). ### Usage `weakEquals(value)` ``` -------------------------------- ### Match function arguments Source: https://github.com/hmil/omnimock/blob/master/README.md Uses matchers to narrow down expectations for function arguments. ```ts when(myMock.someComputation(between(0, 4), same(superComputer), anyString())).return(2); ``` -------------------------------- ### Mocking long call chains Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide Shows how to define behaviors for nested method calls within a mock. ```ts interface ProcessResult { getQuantityOf(ingredient: string): number; } interface FoodPlant { process(...ingredients: Array): ProcessResult; } // ... when(plantMock.process('potato', 'tomato').getQuantityOf('tomato')).return(4); foodPlant.process('potato', 'tomato').getQuantityOf('tomato') === 4; // true ``` -------------------------------- ### Comparison Matchers Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches variables based on numerical comparison: greaterThan, smallerThan, greaterThanOrEqual, smallerThanOrEqual. ```APIDOC ## Comparison Matchers ### Description Matches variables based on numerical comparison. ### Available Matchers - greaterThan(value) - smallerThan(value) - greaterThanOrEqual(value) - smallerThanOrEqual(value) ``` -------------------------------- ### Replace type casts with mockInstance Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide Avoid manual type casting by using mockInstance, which provides a type-safe way to handle partial objects. ```ts const myVegetable: Vegetable = { edible: true } as Partial as Vegetable; // A bad type cast! // Instead, do: const myVegetable = mockInstance('myVegetable', { edible: true }); ``` -------------------------------- ### Match object structure with objectEq Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Performs a recursive match against object members, requiring an exact set of members. ```ts const myMock = mock<(arg: object) => string>(); const test = instance(myMock); when(myMock(objectEq({ name: 'Ola', age: between(30, 40) }))).return('OK'); test({ name: 'Ola', age: 20 })); // Error test({ name: 'Ola' })); // Error test({ name: 'Ola', age: 35, job: 'teacher' })); // Error test({ name: 'Ola', job: 'teacher' })); // Error test({ name: 'Ola', age: 35 })); // OK ``` -------------------------------- ### Match ranges with between Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches variables within a range. Supports inclusive or exclusive boundaries. ```ts match(between(0, 10), 0) // OK match(between(0, 10), 10) // OK match(between({ value: 0, exclusive: true }, 10), 0) // Error match(between(0, { value: 10, exclusive: true }), 10) // Error ``` -------------------------------- ### Type Matchers Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches any variable of the given type: anyNumber, anyBoolean, anyString, anyFunction, anyObject, anySymbol, anyArray. ```APIDOC ## Type Matchers ### Description Matches any variable of the given type. ### Available Matchers - anyNumber() - anyBoolean() - anyString() - anyFunction() - anyObject() - anySymbol() - anyArray() ``` -------------------------------- ### Expect member access Source: https://github.com/hmil/omnimock/blob/master/README.md Sets a specific value for a property access on a mock. ```ts when(myMock.version).useValue(2); ``` -------------------------------- ### not(matcher) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Reverses the result of matching against the provided value. ```APIDOC ## not(matcher) ### Description Reverses the result of matching against the provided value. ### Usage `not(matcher)` ``` -------------------------------- ### Throwing errors from mocks Source: https://github.com/hmil/omnimock/blob/master/README.md Configure a mock to throw an error when a specific method is called. ```ts when(myMock.divide(anyNumber(), 0)).throw(new Error('Division by zero')); // is equivalent to: when(myMock.divide(anyNumber(), 0)).call(() => { throw new Error('Division by zero') }); instance(myMock).divide(22, 0); // throws: Error('Division by zero') ``` -------------------------------- ### contains(object) Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches an object which contains members matching those of the reference. ```APIDOC ## contains(object) ### Description Matches an object which contains members matching those of the reference. ``` -------------------------------- ### Defining custom mock behavior Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide Uses a custom function to dynamically determine the return value based on input arguments. ```ts import { anyString } from 'omnimock'; when(plantMock.process(anyString())).call(i => i.charAt(0) === 'p' ? 4 : 0); foodPlant.process('potato') // 4 foodPlant.process('tomato') // 0 ``` -------------------------------- ### Capture values passed to mocks Source: https://github.com/hmil/omnimock/blob/master/README.md Record arguments passed to a mock method by using a fake call to save the value into a test closure. ```ts let captured: string = ''; when(myMock.getContact(anyString())).call((contact) => { captured = contact; return mockInstance(); }); instance(myMock).getContact('Mom'); expect(captured).toBe('Mom'); ``` -------------------------------- ### Mock deeply nested properties Source: https://github.com/hmil/omnimock/blob/master/README.md Configures expectations for deeply nested object paths or forwards calls to actual implementations. ```ts when(myMock.members.getByName('Steve').job.getCompany().name).useValue('Pixar'); ``` ```ts when(myMock.members.getByName('Steve').job.getCompany().name).useActual(); ``` -------------------------------- ### Update mock attributes incrementally Source: https://github.com/hmil/omnimock/blob/master/README.md Add necessary attributes to a mock instance as they are discovered during testing. ```ts when(codex.getCard('Starlight')).return(mockInstance('fake card', { id: 1038 })); // Or: when(codex.getCard('Starlight')).return(mockInstance(MtgCard, { id: 1038 })); ``` -------------------------------- ### Match object subset with contains Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Matches objects that contain at least the members specified in the reference. ```ts const myMock = mock<(arg: object) => string>(); const test = instance(myMock); when(myMock(contains({ name: 'Ola', age: between(30, 40) }))).return('OK'); test({ name: 'Ola', age: 20 })); // Error test({ name: 'Ola' })); // Error test({ name: 'Ola', age: 35, job: 'teacher' })); // OK test({ name: 'Ola', job: 'teacher' })); // Error test({ name: 'Ola', age: 35 })); // OK ``` -------------------------------- ### Reverse matching with not Source: https://github.com/hmil/omnimock/blob/master/MATCHERS.md Inverts the result of the provided matcher. ```ts match(not(between(0, 10)), 2) // Error match(not(between(0, 10)), 30) // OK match(not('bird'), 'bird') // Error ``` -------------------------------- ### Reset mock expectations Source: https://github.com/hmil/omnimock/blob/master/README.md Clear all or specific expectations from a mock using the reset function. ```ts import { reset } from 'omnimock'; when(myMock.getName()).return('apollo'); when(myMock.luckyNumber).useValue(23); // Reset all expectations set on this mock reset(myMock); instance(myMock).getName(); // Error: Unexpected access to getName instance(myMock).luckyNumber; // Error: Unexpected access to getName when(myMock.getName()).return('apollo'); when(myMock.luckyNumber).useValue(23); // Reset only the getName member access and leave everything else reset(myMock.getName); instance(myMock).getName(); // Error: Unexpected access to getName instance(myMock).luckyNumber; // 23 ``` -------------------------------- ### Handle generic functions Source: https://github.com/hmil/omnimock/wiki/Quick-start-guide TypeScript generics are lost when mocking functions, requiring explicit casts to maintain type safety. ```ts function myGeneric(t: T): T { return t; } const dict = { hello: 'world' }; const mockGeneric = mock('myGeneric'); // Error: s should be of type 'hello' but it is instead of type 'string' when(mockGeneric('hello')).call(s => dict[s]); // You need an explicit cast to fix this when(mockGeneric('hello')).call(s => dict[s as 'hello']); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.