Search code examples
javascriptaws-appsyncvtl

How to fix "Unexpected token $ in JSON" when using VelocityJS to parse VTL


In order to write unit tests for my AppSync resolvers, I'm using the VelocityJS package to parse the VTL inside of my sam template. However, the VTL template isn't being fully parsed.

The code works fine on AWS, it's the unit tests that are erroring. https://github.com/shepherdwind/velocity.js

#if($util.isNullOrBlank($ctx.result.themePreferences))
    #set($themePreverences = {})
    $util.qr($themePreverences.put("darkMode", "DEFAULT"))
    $util.qr($ctx.result.put("themePreferences", $themePreverences))
#end
$util.toJson($ctx.result)

When using let result = Velocity.parse(template, ctx); the result is the string "$util.toJson($ctx.result)" instead of the JSON value of $ctx.result.

IE:

{ "themePreferences": { "darkMode": "DEFAULT" } }

Solution

  • I believe the reason for the parsing troubles is that util and ctx/context are all AppSync concepts, not VTL ones. As you're using a third party library, they don't know what it means and can't replace them.

    You might find Amplify's new mocking and testing tool helpful: https://aws-amplify.github.io/docs/cli-toolchain/quickstart?sdk=js#mocking-and-testing

    There's also additional third party libraries that do a good job of covering AppSync local development worth checking out, if the above doesn't fit your use case.