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
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
And the CDK code to create the CFN Function resource is: