Avoid export error for AWS CloudFront Function and doing unit tests

213 Views Asked by At

How can I avoid this error: "The CloudFront function associated with the CloudFront distribution is invalid or could not run. SyntaxError: Illegal export statement", and still be able to unit test a function?

Example function for CloudFront function

//myfun.js

function handler (event) {
   return event.request;
}

Test code for jest

const handler = require('./myfun.js');

test('handler runs', () => {
  expect(handler({request: {}})
  ).toStrictEqual({});

});

Running jest, would generate an error like : TypeError: rewrite is not a function

2

There are 2 best solutions below

0
On BEST ANSWER

Due to limitations in CloudFront functions runtime, it is not possible at the moment to run functions with export and other mechanisms.

A quick workaround is to avoid deploying the code from file and read it with an IaC tool that allows preprocessing, eg: cdk.

Example in python cdk

Where the extra line was added at the end of myfun.js

...

module.exports = handler;

And the CDK code to create the CFN Function resource is:

CF_FUNCTION_FILE = "./myfun.js"

output = []
with open(CF_FUNCTION_FILE) as f:
  output += f.readlines()[:-1]  # Skip last line

aws_cloudfront.Function(
  self, "myCFfun",
  code=aws_cloudfront.FunctionCode.from_inline("\n".join(output))
)
1
On

Add this line to your myfun.js

// myfun.js

-------

if(console.error) {
   module.exports = handler;
}

console.error is undefined in cloudfront function, hence the if(console.error) check would ensure that module.exports line only runs in your test and your handler is successfully exported for testing.