Skip to content

Commit

Permalink
feat: cjs support in custom middleware file names (#80)
Browse files Browse the repository at this point in the history
---------

Co-authored-by: Murat Çorlu <flanges-slash0t@icloud.com>
  • Loading branch information
valoricDe and muratcorlu authored Mar 20, 2024
1 parent aaf9925 commit 65c1513
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 6 deletions.
15 changes: 9 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}

function isJsFile(str) {
return !!str.match(/\.c?js$/);
}

function defaultLogger(params) {
console.log(

Check warning on line 20 in index.js

View workflow job for this annotation

GitHub Actions / release

Unexpected console statement
`${chalk.bgYellow.black('api-mocker')} ${
Expand Down Expand Up @@ -164,7 +168,7 @@ module.exports = function (urlRoot, pathRoot) {
};

const returnForPath = function (filePath, requestParams) {
if (filePath.endsWith('.js')) {
if (isJsFile(filePath)) {
logger({
req, filePath, fileType: 'js', config
});
Expand Down Expand Up @@ -217,12 +221,11 @@ module.exports = function (urlRoot, pathRoot) {
if (methodFileExtension === 'auto') {
methodFileExtension = req.accepts(['json', 'xml']);
}
const jsMockFile = `${req.method}.js`;
const staticMockFile = `${req.method}.${methodFileExtension}`;
const wildcardJsMockFile = 'ANY.js';
const wildcardStaticMockFile = `ANY.${methodFileExtension}`;

const methodFiles = [jsMockFile, staticMockFile, wildcardJsMockFile, wildcardStaticMockFile];
const fileExtensions = [methodFileExtension, 'cjs', 'js'];
const jsMockFiles = fileExtensions.map((ext) => `${req.method}.${ext}`);
const wildcardJsMockFiles = fileExtensions.map((ext) => `ANY.${ext}`);
const methodFiles = [...jsMockFiles, ...wildcardJsMockFiles];

const matchedMethodFile = methodFiles.find((methodFile) => fs.existsSync(path.join(targetFullPath, methodFile)));

Expand Down
13 changes: 13 additions & 0 deletions test/api-mocker.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,19 @@ describe('Simple configuration with baseUrl', () => {
});
});

describe('cjs extensions for custom middlewares', () => {
it('responds by simple cjs middleware', (done) => {
request(app)

.get('/api/users/3')
.expect('Content-Type', /json/)
.expect(200)
.expect({
result: 'cjs works'
}, done);
});
});

describe('nextOnNotFound setting', () => {
it('returns correct response when mock is exits', (done) => {
request(app)
Expand Down
5 changes: 5 additions & 0 deletions test/mocks/users/3/GET.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = function (req, res) {
res.json({
result: 'cjs works'
});
};

0 comments on commit 65c1513

Please sign in to comment.