A simple project to show how to test a Node Express app using MNP - Mocha, Nock and Proxyquire. Code coverage is done with Istanbul (now called nyc). Rewire can be used in place of proxyquire to test private JS methods. This app is a very basic currency API.
You can see this app running on Zeit Now, each pull request will have it's own URL.
How it works
GET api works in the following way:
- hit URL
- Checks if the currency exchange rate is in the DB, if yes returns it.
- If rate is not in the db it will query the
currencyconverterapi.comfree API to get the rate.
- Returns the rate back and saves it in the DB too.
To create the db and the table, run the following sql script.
CREATE DATABASE currency CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE IF NOT EXISTS `currency`.`exchange_rates` ( `id` INT NOT NULL AUTO_INCREMENT, `from_currency` CHAR(3) NOT NULL, `to_currency` CHAR(3) NOT NULL, `rate` DECIMAL(12,7) NOT NULL, `on_date` DATE NOT NULL, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE INDEX `rate_on_date_UNIQUE` (`from_currency` ASC, `to_currency` ASC, `on_date` ASC)) ENGINE = InnoDB; INSERT INTO `currency`.`exchange_rates` (`from_currency`, `to_currency`, `rate`, `on_date`) VALUES ('AUD', 'USD', '0.742719', '2018-07-22');
Configs for db like username, password etc are in the
to run the app you can use
docker-compose up the go to
http://localhost:8080/api/convert/AUD/USD/2018-07-23 on the browser. It is using the db on
db4free.net so no need to setup the db locally. If you want to set it up locally change the config
To run the tests inside the container run
docker-compose run web npm t
To run tests just run
npm t to watch test run
npm t -- -w.
To watch specific test(s) run
npm t -- -w -g "exchangeRates get or even
npm t -- -w -g "should use default params if no params are provided and no results in db"
To get the code coverage with Istanbul/nyc execute :
npm run test-cov. You should see the code coverage on the cli.
You can also check the code coverage on code climate.