Unit testing is a useful habit for software developers to adopt. For any project whose code might grow more complex, unit testing can help ensure that the application’s core functionality is maintained even as changes are made.

Even for a relatively small-scale Node.js app, it’s possible to include unit testing by using npm packages like Jest and SuperTest. In this walkthrough, we’ll build a basic API using Sequelize and Express, then add unit tests to ensure that our CRUD endpoints remain intact.

Creating the Sequelize application

We’ll move as quickly as possible through our initial setup in order to get to our unit tests— but we’ll include notes along the way for those who want to know more about using the Sequelize CLI with Express.

Let’s start by installing Postgres, Sequelize, and the Sequelize CLI in a new project folder we’ll call express-api-unit-testing:

mkdir express-api-unit-testing
cd express-api-unit-testing
git init
npm init -y && npm i sequelize pg && npm i --save-dev sequelize-cli

Let’s also add a .gitignore file to ease deployment later:

echo "
/node_modules
.DS_Store
.env" >> .gitignore

Next we will initialize a Sequelize project, then open the directory in our code editor:

npx sequelize-cli init
code .

Let’s configure our Sequelize project to work with a Postgres database. Find config.json in the /config directory and change the code to look like this:

{
  "development": {
    "database": "wishlist_api_development",
    "dialect": "postgres"
  },
  "test": {
    "database": "wishlist_api_test",
    "dialect": "postgres"
  },
  "production": {
    "use_env_variable": "DATABASE_URL",
    "dialect": "postgres",
    "dialectOptions": {
      "ssl": {
        "rejectUnauthorized": false
      }
    }
  }
}

Now we can tell Sequelize CLI to create the Postgres database:

npx sequelize-cli db:create

Defining models and adding seed data

Our demonstration app will associate users with items on a wishlist. Let’s start by creating a User model using the Sequelize CLI:

npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string,password:string

#sequelize #javascript #express api #nodejs #api

How to Build an Express API with Sequelize CLI and Unit Testing
16.45 GEEK