Search code examples
jsonhandlebars.jswiremock-standalone

How to use an if conditional in a WireMock JSON stub?


I need to use if conditional in my stub. I know there are the different scenarios you can create with body patterns but this does not work in my case because I am getting a variable number of objects in the payload and I need to use a for loop to check every one of them. So my request payload would look similar to this:

[
   { "todo_id": 1 },
   { "todo_id": null },
   { "todo_id": 3 }
]

I want to respond with the todo_id where there was one and respond with a random integer where there is null, so my response payload so far is this:

"response": {
    "status": 200,
    "body": "[ {{#each (jsonPath request.body '$') as |todo|}}
                  { \"todo_id\":
                      {{#if (todo.todo_id == null) }}
                          1{{randomValue length=1 type='NUMERIC'}}
                      {{else}}
                          {{todo.todo_id}}
                      {{/if}}
                },
            {{/each}} ]"
}

I know you can't body spaced out like that but I did it to make it easer to read the code.

So the for each loop definitely works, I've tried it without if statement and it works fine. But I cannot get the if statement working for me.

Any ideas on how to implement something like this?


Solution

  • Okay so I got an answer for this on Google Group for WireMock.

    Apparently to compare values you're supposed to use eq operator.

    So changing my conditional part of the code to look like this

    {{#eq todo.todo_id null}}
        1{{randomValue length=1 type='NUMERIC'}}
    {{else}}
        {{todo.todo_id}}
    {{/eq}}
    

    solved the problem.