0

I have a question regarding the decoration of response of mountebank. I failed to call a function from another js file in the response code block. Anyone could give me a hint?

My js file: utils.js

function getRandomCharAndNum(min, max){
    let returnStr = "";
    const range = (max ? Math.round(Math.random() * (max-min)) + min : min);
    const charStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for(let i=0; i<range; i++){
        const index = Math.round(Math.random() * (charStr.length-1));
        returnStr = returnStr + charStr.substring(index,index+1);
    }
    return returnStr;
}

The response code in mountebank is

const utils = require('./utils/utils');
responses: [{
    is: {
        statusCode: 200,
        headers: {
            "Consent-Type": "application/json"
        }
    },
    _behaviors: {
        decorate: `(config) => {
                config.response.body = { 
                   id: utils.getRandomCharAndNum()
                 };
        }`
    }
}]

The error is: {"errors":[{"message":"Converting circular structure to JSON","name":"TypeError","stack":"TypeError: Converting circular structure to JSON\n at JSON.stringify (<anonymous>)\n at responsePromise.then.response (/Users/xinxing.cheng/Documents/app/node_modules/mountebank/src/models/behaviors.js:251:48)\n at _fulfilled (/Users/xinxing.cheng/Documents/app/node_modules/q/q.js:854:54)\n at /Users/xinxing.cheng/Documents/app/node_modules/q/q.js:883:30\n at Promise.promise.promiseDispatch (/Users/xinxing.cheng/Documents/app/node_modules/q/q.js:816:13)\n at /Users/xinxing.cheng/Documents/app/node_modules/q/q.js:877:14\n at runSingle (/Users/xinxing.cheng/Documents/app/node_modules/q/q.js:137:13)\n at flush (/Users/xinxing.cheng/Documents/app/node_modules/q/q.js:125:13)\n at process._tickCallback (internal/process/next_tick.js:61:11)"}]}

  • 1
    Your error is unrelated to your question title. The issue here is that somewhere, you or your dependencies is trying to use `JSON.stringify` on an object that has a circular reference (i.e. a sub-property that references its parent) – Seblor Nov 15 '19 at 09:08

1 Answers1

1

You have to either inline the getRandomCharAndNum function to the decorate function, or include it inside the decorate function directly. It looks like you have some wrapper (not shown) that calls mountebank, but you can't include the relevant helper function outside the decorator.

bbyars
  • 406
  • 3
  • 3
  • Thank you Brandon Byars@bbyars, I include getRandomCharAndNum function inside decorate function and it worked. And I am wondering how could I encapsulating function in mb? I have some services need to mock and some function are similar. So I want to pick up them and don't need to write in each service. That's why I want to know to call another js function in the mb. Could you give me some hint? – Xinxing Cheng Nov 19 '19 at 01:24