@ephesoft/mock.engine
v1.1.1
Published
Framework for easily creating mock objects
Downloads
4
Keywords
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. |