Hi all! Trying to write a unit test for my lambda ...
# help
e
Hi all! Trying to write a unit test for my lambda code, but I need a DynamoDB table to run the lambda against (pulled from process.env.TABLE_NAME). Is there a best practice for how to do this?
new MyStack(app, "test-stack")
and then pull the table name out of the stack somehow? Run dynamodb-local? It seems I'm missing something obvious here...
r
You can create a table using the Table construct and assign the value of someTable.tableName to your env var
e
Oh, that easy? The Table doesn't need to be in a Stack and App?
r
Yeah, it'll need to be in a stack
e
Right. I'll try and see if I get it going. Thanks!
r
np
j
@Emil Styrke when writing unit tests for lambda code, you should be mocking the dynamodb sdk
e
@Joe Kendal Good point. I think what I'm really looking for is integration tests (for my AppSync API), but it seemed tricky to get going, so I settled for testing as much as possible using the existing Jest setup. But I should really be doing both, and unit tests should mock the underlying layers as you say. Any pointers for the integration/E2E tests would be helpful as well (i.e. how to set up a test stack and somehow get the resulting API endpoint to make requests against).
j
@Emil Styrke we have to trust that the AWS service does what we tell it to. Other than that we can only do E2E testing. To be honest I am at the same stage as you. I need to do E2E tests before launch. I am paranoid something will break in Production. Here’s what I am thinking of doing: 1. Using @aws-cdk/pipelines package, we can add a Stage (e.g. “Pre-prod”, “Gamma”, “QA”, “Test” - whatever I should call it 🤷🏻‍♂️). 2. Using the .addStage() method, we can specify pre-hook or post-hook commands. These take the form of string[] bash commands from the current working directory. (So you will have access to the repository of your cdk app) 3. Therefore we can do something like run scripts inside a test folder 4. Theoretically we can use any language or framework for this. I am thinking of using Golang with AWS-SDK. It’s important that we access the stack outputs. There are examples in the new cdk pipelines docs
The examples of accessing the stack outputs in a post-deployment script are in this page https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html