Skip to content

Node.js + MySQL + Jest

Here’s an example MySQL library in Node.js using promises and Jest tests to create a table, populate it, and read it back:

First, make sure to install the mysql and jest packages:

Next create a file named mysql.js and add the following code

This code exports three functions: dropTable, createTable, populateTable, readTable and closeDatabase which respectively create a new table, populate the table with sample data, and read the contents of the table.

Next, create a Jest test file named mysql.test.js and add the following code:

This test file imports the mysql module, creates the table and populates it with sample data before all tests, and deletes the table after all tests have run. It then tests that the readTable function returns the correct data.

To run jest make sure you have added the command to run jest in the scripts section of you package.json file. This is created automatically for you when you run npm init

To run the tests, run the following command:

There you have a simple but effective starter for 10 creating a node.js MySQL library for your javascript app.

Leave a Reply

Your email address will not be published. Required fields are marked *