I have read this article
https://community.apigee.com/articles/3964/unit-testing-javascript-code-with-mocha-sinon-and.html
like the one from the article for example
try { var responseCode = parseInt(context.getVariable('response.status.code')); var log = { org: context.getVariable('organization.name'), env: context.getVariable('environment.name'), responseCode: responseCode, isError: (responseCode >= 400) }; if (log.isError) { log.errorMessage = context.getVariable('flow.error.message'); } var logglyRequest = new Request( 'https://loggly.com/aaa', 'POST', {'Content-Type': 'application/json'}, JSON.stringify(log) ); httpClient.send(logglyRequest); } catch (e) {}
The thing is that when I try to 'require' the js file I get nothing.
And only when I add 'module.exports' I get the file.
1. Am I not importing this the right way?
2. The problem is that apigee js object model doesn't recognize 'module.exports' so I cant leave it that way. what should I do?
We do lots of unit testing / code linting in our JavaScript and the best advice I could give you is to isolate the use of apigee context variables into files that you do not directly unit test.
For example, given a transformation you may actually use two files... one call Script-SomethingExecute.js and the second Script-Transform.js
In Script-SomethingExecute.js you may have something like
var requestString, oldJSON, transformedResponse, error; requestString = context.getVariable('response.content'); onldJSON = targetResponseToJSON(requestString); error = checkInitResponseError(onldJSON); if (error.isError) { context.setVariable('llbean.isError', error.isError); context.setVariable('llbean.errorCode', error.code); context.setVariable('llbean.errorMessage', error.message); } else { transformedResponse = jsonTransform(onldJSON); context.setVariable('response.content', JSON.stringify(transformedResponse)); }
There isn't much going on here to test because all the hard work is done in the targetResponseToJSON, checkInitResponseError and jsonTransform.
By isolating the testable code in Script-Transform.js file and making sure all the apigee context stuff put stuff in plain JS vars it may work for you.
User | Count |
---|---|
7 | |
2 | |
2 | |
1 | |
1 |