Controllers
Unit Testing
The smallest parts of an application are called units. The testing of those units to check whether it is fit for use or not is called unit testing.
If we are going to create a test for any function, we need to make sure that the function by itself, separate from everything around, should do what it is intended to do, not more, not less, and mock rest of things which are not under test. And that’s basic principle of unit test.
We use three npm modules to do this. They are mocha, sinon, and chai.
Let’s start by installing the npm modules we are going to need. Run “npm install –save-dev mocha”, “npm install –save-dev sinon” and “npm install –save-dev chai”. We save them as devDependencies because they are only used for testing.
Mocha is the framework that these test run on, so this manner of unit testing is called mocha testing. Mocha adds functions like describe and it. You will learn more about them later. If you have further questions you can check out the documentation here: https://mochajs.org/
Sinon allows you to send and receive fake data so your tests don’t mess with actual things. You can find out more about Sinon here: https://sinonjs.org/
Chai is an assertion library. You can learn more here: https://www.npmjs.com/package/chai
Let’s also make files for our tests called “add-person-test”, “delete-person-test”, “get-person-test”, and “modify-person-test” in a file called “test”.
Let’s also modify our buildspec.yml file to run the test that we make.
Now our web service won’t get deployed unless it passes our test.
Writing Controllers
Let’s get ready to rewrite our controllers so they can access your new DynamoDB. We are going to use AWS SDK again.
Let’s start by initializing a “Document Client”, which allows us to interact with the DynamoDB in a simple manner. You can see more about it here: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html
Go to your “favoriteColor” application and initialize it.
After the section where you export everything, we are going to need to create a variable that that tells it what the table is named.
The ||
says if you can’t find the table on your own, here’s what it should be named. This allows you to access the database locally.
One more thing. Remember how we exported all our functions at the beginning of our program?
From here on out, we are going to export them differently. So we can delete them from our code.