Unit testing of JavaScript Policy

Is there a way to unit test the variables in JavaScript code.

I don't know how to mock response.content.asXML etc work from within a unit test. Is there a way to mock these variables.

I have been able to mock context.getVariable() and context.setVariable using mocha framework

Solved Solved
0 4 1,214
1 ACCEPTED SOLUTION

I would use a separate file with mock response and pass it to the mocha script to validate against some tests. Would that work ?

View solution in original post

4 REPLIES 4

I would use a separate file with mock response and pass it to the mocha script to validate against some tests. Would that work ?

There's an example of unit testing of javascript for an api with mocking of context variables

https://raw.githubusercontent.com/apigee/maven-jenkins-ci-demo/master/currency-v1/test/unit/loggly.j...

Hi @shriyashrivasta ,

   can you please provide one sample test code for mocking context.getVariable and SetVariable Function?

    I have followed the ways which are provided in below links but that doesn't worked for me I always ended up with 

     context.getVariable is not a function

https://www.googlecloudcommunity.com/gc/Apigee/Getting-a-ReferenceError-when-unit-testing-with-Mocha... 

https://raw.githubusercontent.com/apigee/maven-jenkins-ci-demo/master/currency-v1/test/unit/loggly.j... 

 

In general it's a bad practice to ask new questions in responses to questions that are several years old. The problem is new questions often are different from the original, and with responses and more questions, the conversation drifts away from the original.  That makes it hard to navigate this forum for future readers. It devalues the forum as a knowledge base. 

So in general I don't answer new questions posed in responses to old questions. And I try to discourage other people from answering, too! 

But in this case, your question is directly related to the original. So i figured a new answer might help.  Here's a repo that shows you how to mock the objects for testing of JavaScript for Apigee JS Callouts. 

https://github.com/apigee/devrel/tree/main/references/js-callout