Interface IMock<T>

The main API of the framework.

Example


const value = 'value';
const object = new Mock<Function>()
.setup(instance => instance(1))
.returns(value)
.object();

const actual = object(1);

expect(actual).toBe(value);

Latest setups have more precedence over earlier setups.

Example


const object = new Mock<Function>()
.setup(instance => instance(1))
.returns(1)
.setup(instance => instance(1))
.returns(2)
.object();

const actual = object(1);

expect(actual).toBe(2);

Type Parameters

  • T

    The type of mocked object. Could be any type including:

    • Function,
    • arrow function,
    • interface,
    • class,
    • object and etc.

Hierarchy

  • IMock

Implemented by

Properties

name?: string

You can name the mock. The name will be displayed with any relative output, so you can easily distinct output of several mocks. On the mocked object you can find this name at 'mockName' property of the [[Handler]].

options: IMockOptions<T>

Returns options object

tracker: Tracker

Returns the tracker object that responsible for storing history of interactions with the mocked object.

Methods

  • Set the prototype of the mocked object.

    Example


    class PrototypeClass {}

    const mock = new Mock<{}>();
    const object = mock.object();

    Object.setPrototypeOf(object, PrototypeClass.prototype);

    expect(object instanceof PrototypeClass).toBe(true);

    Parameters

    • Optional prototype: any

    Returns IMock<T>

  • Retrieves an instance from the injector based on the provided token.

    Type Parameters

    Parameters

    Returns R

    The instance from the injector if defined, otherwise null.

  • Defines a configuration for particular interaction with the mocked object.

    Example


    // a function invoke with 1 as parameter
    .setup(instance => instance(1))

    // apply function invoke on a function with null as the first parameter and a placeholder for the second parameter
    .setup(instance => instance.apply(null, It.IsAny()))

    // accessing to a property
    .setup(instance => instance.property)

    //accessing to a named function with name 'test' of an object and the first parameter is 1
    .setup(instance => It.Is((expression: NamedMethodExpression) => {
    return expression.name === 'test' && expression.args[0] === 1
    }))

    //setting propertyA to value of 'a'
    .setup(instance => {instance.propertyA = 'a'})

    Type Parameters

    • E extends IExpression<T>

    • R = E extends ((...args) => M)
          ? M
          : any

    Parameters

    • expression: E

      A function that accepts a Proxy and either plays expected interaction or returns a predicate function. Refer It class for parameter placeholders or predicate functions. Refer the integration tests for more examples.

    Returns IPresetBuilder<T, R>

    PresetBuilder config interface for the provided expression.

Generated using TypeDoc