@betheweb/mockme-plugin-js
v0.1.4
Published
A mockme plugin to load mocks from js files
Downloads
3
Maintainers
Readme
mockme-plugin-js
A mockme plugin to include mocks in JS files.
How to install
Install with NPM
$ npm i -D @betheweb/mockme-plugin-js
Install with Bun
$ bun add -D @betheweb/mockme-plugin-js
Install with PNPM
$ pnpm add -D @betheweb/mockme-plugin-js
How to use it
Just import it in the mockme config file and add it to the plugins section.
import mockmePluginJs from '@betheweb/mockme-plugin-js';
export default {
plugins: [mockmePluginJs()],
};
This plugin does not transform the code in the source files, so the mocks generated by them should follow the mockme mocks schema. If the file exports a function, the function will be invoked and the config will be passed to it.
Configuration
input
Input accepts either a single path or an array of paths where each of them points to a file. Paths can also be a glob expression.
Example:
import mockmePluginJs from '@betheweb/mockme-plugin-js';
export default {
plugins: [
mockmePluginJs({
input: ['demo/mocks.js', 'fixtures/*.mock.js'],
}),
],
};
Mock files
These are examples of files that will return valid mocks:
Example of single mock object:
export default {
request: {
method: 'GET',
path: '/api/v1/books/:id',
},
response: ({ params }) => {
if (params.id < 0) {
return {
body: { message: `Id ${params.id} is not a valid identifier.` },
status: 404,
};
} else {
return {
body: { id: params.id, title: 'Mr. Fox' },
};
}
},
};
Example of multiple mock objects:
export default [
{
tags: ['foo', 'bar'],
request: {
method: 'GET',
path: '/api/v1/books/:id',
},
response: ({ params }) => ({
body: {
id: params.id,
title: 'Mr. Fox',
},
}),
},
{
request: {
method: 'GET',
path: '/api/v2/books/:id',
},
response: ({ params }) => ({
body: {
id: params.id,
title: 'Mr. Fox',
pages: 123,
},
}),
},
];
Example using a function to generate mocks:
export default function (config) {
return [
{ id: 1, title: 'Mr. Fox' },
{ id: 2, title: 'Harry Potter' },
].map(({ id, title }) => ({
request: { method: 'GET', path: `/api/v1/books/${id}` },
response: { body: { id, title } },
}));
}