npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ephesoft/mock.engine

v1.1.1

Published

Framework for easily creating mock objects

Downloads

4

Readme

README

Consuming this package

Add the package to your repository:

npm i @ephesoft/mock.engine --save-dev

API documentation may be generated with npm run docs (HTML) or npm run docs:bitbucket (MD).

Limitations

  • This framework is for mocking functions only. It won't work for fields and getters/setters.
  • The engine works in the overwhelming majority of cases we've tried but it can get confused on complex types.

Mocking an Interface

Assume we want to mock the UserStore interface as defined below:

export interface UserStore {
    // synchronous - no parameters - void return type
    deleteAllUsers(): void;

    // asynchronous - multiple parameters - non-void return type
    addUser(email: string, firstName: string, lastName: string): Promise<User>;
}

export interface User {
    email: string;
    firstName: string;
    lastName: string;
}

Our implementation would look like the following:

export class MockUserStore extends MockBase<MockUserStore, Pick<UserStore, 'deleteAllUsers' | 'addUser'>> implements UserStore {
    public constructor(options?: MockOptions) {
        // Note that the base class needs to know the name of this mock class
        super('MockUserStore', options);
    }

    // #region mocked functions

    public deleteAllUsers(): void {
        super.processCall('deleteAllUsers', []);
    }

    public async addUser(email: string, firstName: string, lastName: string): Promise<User> {
        return Promise.resolve(super.processCall('addUser', [email, firstName, lastName]));
    }

    // #endregion mocked functions
}

Mocking a Class

Assume we want to mock the UserStore class as defined below:

export class UserStore {
    // synchronous - no parameters - void return type
    public deleteAllUsers(): void {
        // ...
    }

    // asynchronous - multiple parameters - non-void return type
    public async addUser(email: string, firstName: string, lastName: string): Promise<User> {
        // ...
        return Promise.resolve({ email, firstName, lastName });
    }
}

export interface User {
    email: string;
    firstName: string;
    lastName: string;
}

Our implementation would look like the following:

type MockedFunctions = Pick<UserStore, 'deleteAllUsers' | 'addUser'>;
export class MockUserStore extends UserStore {
    readonly #mockEngine: MockEngine<MockedFunctions>;

    public constructor(options?: MockOptions) {
        super();
        // Note that the engine needs to know the name of this mock class
        this.#mockEngine = new MockEngine<MockedFunctions>('MockUserStore', options);
    }

    // #region mocked functions

    public deleteAllUsers(): void {
        this.#mockEngine.processCall('deleteAllUsers', []);
    }

    public async addUser(email: string, firstName: string, lastName: string): Promise<User> {
        return Promise.resolve(this.#mockEngine.processCall('addUser', [email, firstName, lastName]));
    }

    // #endregion mocked functions

    // #region boilerplate

     public reset(): MockUserStore {
        this.#mockEngine.reset();
        return this;
    }

    public getCalls<T extends keyof MockedFunctions>(functionName: T): Parameters<MockedFunctions[T]>[] {
        return this.#mockEngine.getCalls(functionName);
    }

    public expectCall<T extends keyof MockedFunctions>(
        functionName: T,
        response?: BaseReturnType<MockedFunctions[T]> | Error | Synchronous<MockedFunctions[T]>,
        options?: ExpectationOptions
    ): MockUserStore {
        this.#mockEngine.expectCall(functionName, response, options);
        return this;
    }

    public expectCalls<T extends keyof MockedFunctions>(
        functionName: T,
        ...responses: (BaseReturnType<MockedFunctions[T]> | Error | Synchronous<MockedFunctions[T]>)[]
    ): MockUserStore {
        this.#mockEngine.expectCalls(functionName, ...responses);
        return this;
    }

    // #endregion boilerplate
}

Using the Mock

Assuming we created the mock in the previous section, we can use it as follows:

We can then configure the mock as follows:

    const mock = new MockUserStore(); // Create a mock with call capture enabled

    // set single expectation which returns a value
    mock.expectCall('addUser', { email: '[email protected]', firstName: 'John', lastName: 'Doe' });

    // set an expectation which will throw an error when called
    mock.expectCall('addUser', new Error('Boom!'));

    // set expectation which will return the same value 5 times
    mock.expectCall(
        'addUser',
        {
            email: '[email protected]',
            firstName: 'Sally',
            lastName: 'Johnson'
        },
        { repeat: 5 }
    );

    // set multiple expectations at the same time
    mock.expectCalls(
        'addUser',
        {
            email: '[email protected]',
            firstName: 'Sally',
            lastName: 'Johnson'
        },
        {
            email: '[email protected]',
            firstName: 'John',
            lastName: 'Doe'
        },
        new Error('Write Failure')
    );

    // defer the call to a custom handler function for 2 calls
    mock.expectCall(
        'addUser',
        (email: string, firstName: string, lastName: string): User => {
            console.log(`email: ${email}; firstName: ${firstName}; lastName: ${lastName}`);
            return { email, firstName, lastName };
        },
        { repeat: 2 }
    );

    // set expectation which will return the same value every time
    mock.expectCall(
        'addUser',
        {
            email: '[email protected]',
            firstName: 'Sally',
            lastName: 'Johnson'
        },
        { repeat: true }
    );


    // get the calls made to addUser so we can validate them.
    // Each item in the array is a tuple containing the parameters passed to the function.
    const addUserCalls: [email: string, firstName: string, lastName: string][] = mock.getCalls('addUser');
    

    // reset the mock to a freshly-created state
    mock.reset();

Development

Files that must be updated

IMPORTANT: The following files should be updated with every change:

  • package.json ($.version property) - use semantic versioning
  • package-lock.json ($.version property) - must match version in package.json
  • changelog.md - Should include the version and a description of the changes
  • readme.md - Review this file to see if changes are needed

NPM run targets

Run NPM commands as

npm run command

Available Commands

|Command|Description| |:-|:-| | audit | Executes a dependency audit using the default NPM registry | | audit:fix | Attempts an automatic fix of any audit failures. | | build | Cleans the dist folder and transpiles/webpacks the code | | clean | Deletes the working folders like dist and docs | | clean:docs | Deletes the docs folder | | create:beta | Auto versions the package to the next available beta version. | | docs | Create API documentation for the package in a "docs" folder | | docs:bitbucket | Creates API documentation in Bitbucket markdown format in a "docs" folder | | lint | Performs static analysis on the TypeScript files. | | lint:fix | Performs static analysis on the TypeScript files and attempts to automatically fix errors. | | lint:report | Performs static analysis on the TypeScript files using the default validation rules and logs results to a JSON file. | | pack | Creates a local tarball package | | postbuild| Automatically ran during build. | | postprepare | Automatically ran during package install to setup tooling. | | prebuild | Automatically ran during build. | | start | Instructs the TypeScript compiler to compile the ts files every time a change is detected. | | test | Executes all tests and generates coverage. | | test:coverage | Generates code coverage reports from test data. | | test:unit | Runs the unit tests. | | validate:ga | Validates the package version is valid for GA release. | | validate:beta | Validates the package version is valid for a Beta release. |