Definitive Guide to Getting Started with Travis CI

Published:24 June 2022 - 11 min. read

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

Have you ever thought of implementing Continuous Integration and Continuous Deployment (CID/CD) with Travis CI in your project? Learning a new tool can be daunting. But don’t worry! You’ve come to the right place.

Travis CI is a Software as a Service (SaaS), where you can add your project from GitHub to be tested in a specific environment and deployed to a particular environment. And in this tutorial, you’ll learn how to implement CI for a Node application and automate CD to Heroku.

Ready? Get started with Travis CI and take it for a spin!

Prerequisites

This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:

  • A GitHub account with a public repository – This tutorial uses a public GitHub repository named travis-ci-project.
  • A code editor – This tutorial uses Visual Studio Code (VS Code).
  • A computer with any OS will work – This tutorial uses Ubuntu 20.04.

Creating a Node-based Project

You’ll first need a project before creating a CI/CD pipeline with Travis CI. So you’ll create a Node-based project for this tutorial. You’ll crisply go through how the application is built, write test cases, and then push it to GitHub.

1. Open your terminal, and run the following commands to create a working directory (mkdir) and switch (cd) to that directory. You can name the directory as you like, but this tutorial’s choice is node-TravisCI

mkdir node-TravisCI
cd node-TravisCI
Creating a working directory (node-TravisCI)
Creating a working directory (node-TravisCI)

2. Next, open your working directory using your favorite code editor. The command below doesn’t have output but opens your working directory on VS Code.

code .

3. Run the below npm init command to initialize a package.json file to track necessary metadata about your Node project.

npm init

Either provide answers to the following prompts or press Enter to bypass them.

You’ll see an output similar to the one below on successful creation.

Verifying the successful creation of the package.json file
Verifying the successful creation of the package.json file

4. Now, run the npm install command below to install the following:

  • express - Express is a Node.js framework that builds single-page, multi-page, and hybrid web applications.
  • body-parser - Body-parser parses incoming request bodies in a middleware so that relevant information can be extracted easily.
npm install express body-parser

The output below indicates that both packages are installed successfully on your Node project.

Verifying successful installation of express and body-parser
Verifying successful installation of express and body-parser

5. Lastly, run the below command to install the following testing libraries:

  • jestJest is a library used for testing Node applications.
  • supertest - Super-test is a library used for testing Node.js HTTP servers.
npm install --save-dev jest supertest

Once installed, you’ll get the following output.

Installing Jest and Super-test libraries
Installing Jest and Super-test libraries

Implementing Code and Testing the Application

Now that you have all the libraries needed for the Node application, it’s time to implement some JavaScript code. You’ll create JavaScript files that make up your application and later test if the application is working.

1. On your working directory (~/node-TravisCI), create a file called index.js with your code editor, and add the following code.

The code below creates a web application that listens on port 4000 and prints the Hello world from Travis message.

// Importing the express library
const express = require('express')

//Intializing an express app
const app = express()

const port  = process.env.PORT || 4000;

app.get('/', (req, res) => {
  res.status(200).json('Hello world from Travis')
})

// Exporting the home route so it can be tested
module.exports = app.listen(port, () => console.log(`Your application is running on ${port}`))

2. Next, create a file called route.spec.js, and populate the following code (test case).

The code below has a description of page should return hello world travis that expects the body to say Hello world from Travis.

const request = require('supertest') //importing the supertest library
const app = require('./index.js') //importing the 'index.js' file

describe('Get route', () => {
  it('page should return hello world travis', async () => {
    const res = await request(app).get('/')
    expect(res.statusCode).toEqual(200)
    expect(res.body).toEqual('Hello world from Travis')
  })
})

afterAll(async () => { await app.close() })

3. Edit your package.json file, and replace the scripts code block with the following:

This code lets npm test and npm start commands to run your tests and start your Node application.

  "scripts": {
    "test": "jest",
    "start": "node index.js"
  },
Enabling the npm test and npm start commands
Enabling the npm test and npm start commands

4. Now, run the npm start command below to run your application.

npm start

You’ll see the following output, which says your application is running on port 4000.

Running Node application on port 4000
Running Node application on port 4000

5. Press Ctrl+C to stop the application from running, and run the npm test command below to confirm if your tests are passing.

npm test

If you have your tests passing correctly, you’ll see the following output.

Verifying tests are passing
Verifying tests are passing

6. Next, create a .gitignore file in your working directory (~/node-TravisCI), and add node_module in the file, as shown below. Doing to tells Git to ignore the node_module folder, as it’s not good practice to include this folder when pushing your repository to GitHub.

Making Git ignore the node_module folder when pushing
Making Git ignore the node_module folder when pushing

7. Lastly, create a file called Procfile, and add the following command.

This command is required for a Heroku app to execute on start-up since you aim to deploy the Node application to Heroku.

web: node index.js
Adding an executable command in (Procfile)
Adding an executable command in (Procfile)

Pushing Repository to GitHub

Your Node application is all set at this point, so it’s time to push your repository (node-TravisCI) to GitHub. Pushing your repository to GitHub (as the source of truth) is crucial. Doing so lets you deploy your Node application to Heroku and GitHub pages later on with Travis CI.

1. On your terminal, run the git init command below to initialize the working directory as your Git repository.

Initializing a Git repository
Initializing a Git repository

2. Next, run the following commands (git add and git commit) to enable Git to track files and add your first commit.

git add .
git commit -m 'first commit'
Performing first commit
Performing first commit

3. Finally, run the below commands (git remote and git push) to perform the following:

  • Add your remote Git repository. Be sure to replace mercybassey/travis-ci-project.git with your own remote Git origin URL.
  • Push the changes to your master branch on your Git repository.
# Add your remote Git repository
git remote add origin [email protected]:mercybassey/travis-ci-project.git
# Push changes to the master branch
git push origin master

If pushed successfully, you’ll see the following output:

Pushing commit to the master branch of the Git repository
Pushing commit to the master branch of the Git repository

Signing Up to Travis CI

Now that your Node application is ready and pushed to your Git repository, you’re ready to get started with Travis CI. But before creating a CI/CD pipeline, you’ll have to sign up for a Travis CI account.

1. Open your favorite web browser, and navigate to Travis CI official website.

2.Click the Start Today button on the homepage to initialize creating an account.

Initializing creating a Travis CI account
Initializing creating a Travis CI account

3. On the Sign up page, click SIGN UP WITH GITHUB as your signup method since you already have your source code on GitHub.

Signing up for Travis CI with (GitHub)
Signing up for Travis CI with (GitHub)

4. Now, click on Authorize Travis CI to give Travis CI permission to access your GitHub account.

Authorizing Travis CI access to your GitHub account
Authorizing Travis CI access to your GitHub account

5. Click the ACTIVATE ALL REPOSITORIES USING GITHUB APPS button to activate your GitHub repositories. Doing so gives Travis CI access to your GitHub repositories.

Activating all repositories using (GitHub Apps)
Activating all repositories using (GitHub Apps)

6. Next, click Approve & Install to install Travis CI on your GitHub account. Once installed, your browser redirects to a page where you’ll need to insert your GitHub password.

Automatically, you’ll be logged in to Travis CI.

Approving and installing Travis CI on GitHub

On successful login, you’ll get to your Travis CI dashboard to see your GitHub repositories, as shown below.

Viewing GitHub repositories in Travis CI
Viewing GitHub repositories in Travis CI

7. Click on the Plan tab to see all the plans available for Travis CI. You’ll need to select a plan before you can use Travis CI.

Viewing Git repositories and initializing choosing a plan
Viewing Git repositories and initializing choosing a plan

8. Select the free plan to continue.

Selecting a free plan on Travis CI
Selecting a free plan on Travis CI

9. Populate the fields with the required information, and click on the Proceed to payment button to validate the information.

Adding contact and billing details to Travis CI
Adding contact and billing details to Travis CI

10. On successful validation, click on Dashboard to access your Travis CI dashboard and view your builds. As a new user, you’ll see no builds at this stage, just like the image below.

Viewing builds on Travis CI dashboard
Viewing builds on Travis CI dashboard

11. Now, click on your profile icon shown below, and select the Settings option to switch back to your Travis CI account page.

Initializing selecting GitHub repository
Initializing selecting GitHub repository

12. Search for your GitHub repository (travis-ci-project) that houses your Node application.

Searching and selecting the GitHub repository (travis-ci-project)

You should have the following output, which indicates you have no builds yet.

Viewing Git repository (travis-ci-project) on Travis CI
Viewing Git repository (travis-ci-project) on Travis CI

Creating and Running a Build

Now that you have an active Travis CI account, the following line of action is to create a build for your Node application.

Travis CI uses a .travis.yml file to create your builds. The .travis.yml file will contain all configurations and tasks that Travis CI will perform. So this file is what Travis CI will watch out for to perform builds.

1. On your project directory, create a file called .travis.yml and add the following code to the file.

# Set the language Travis CI should expect.
language: node_js

# Set the Node.js version you’d like Travis to use. Add more versions as you like.
node_js:
- 18.3.0 

# Cache all npm dependencies so Travis CI only installs dependencies once.
# For multiple builds, caching all npm dependencies enables your builds to run faster.
cache: npm

# Configure the build cycles to tell Travis CI to install all dependencies.
# You can also add other dependencies you like Travis to install globally.
install: # Hook provided by Travis CI
- npm install

# Tell Travis CI to run the test for your Node application
script:
- npm test 

2. Next, run the commands below to run your build, track the changed files, and commit to your GitHub repository.

Running your build will be less hassle since you already have Travis CI synced to your GitHub repositories.

# Track changed files
git add .
# Add a commit message
git commit -m 'added a .travis.yml file to run a build'
Adding commit message to remote Git repository
Adding commit message to remote Git repository

3. Now, run the below command to push the changes to the master branch of your remote Git repository.

git push origin master

Once pushed, you’ll see an output similar to the one below.

Pushing changes to remote Git repository
Pushing changes to remote Git repository

4. Lastly, switch back to your Travis CI dashboard, and the following output indicates your build is received.

Processing builds in Travis CI
Processing builds in Travis CI

And once Travis CI has successfully performed all tasks listed in the .travis.yml file, you’ll get an output saying that your build is ready.

You have now successfully run a build to completion!

Creating a build to completion in Travis CI
Creating a build to completion in Travis CI

Configuring Travis CI for Build Deployment

Your build on Travis CI is running, and you’re almost ready to deploy your build. But first, you’ll need to add some configuration settings to tell Travis CI to deploy your application to Heroku.

You’ll add these configuration settings to your .travis.yml file under the deploy hook.

1. Open your .travis.yml file, and add the following configuration to the bottom of the file’s content.

This configuration below tells Travis CI to deploy your application to Heroku.

# Install the Faraday library, which is required before deploying the build to Heroku
before_deploy:
  - rvm $(travis_internal_ruby) --fuzzy do ruby -S gem install faraday -v 1.8.0
deploy:
  provider: heroku # Tell Travis CI to deploy your application to Heroku.
  skip-cleanup: true
  api_key: $HEROKU_TOKEN # The environment variable you'll create later for a token.
	app: node-travis-app # Tells deployment should be made for the app node-travis-app.
  

2. Next, run the below command to login into your Heroku account since you’ll need to create an application on Heroku and generate a Heroku authentication token.

heroku login

Input your Heroku username and password when prompted. Once connected, a login page opens on your web browser (step two).

Logging into the Heroku account
Logging into the Heroku account

3. Click on Log In to continue logging in to Heroku CLI.

Logging into Heroku CLI via a web browser
Logging into Heroku CLI via a web browser

You’ll see the following page once you’ve successfully logged in.

Confirming successful login to the Heroku CLI
Confirming successful login to the Heroku CLI

Also, on your terminal, you’ll see the following message saying you’re logged in on the Heroku CLI.

Verifying login on Heroku CLI
Verifying login on Heroku CLI

4. Once logged in, run the heroku create command below to create a Heroku application called node-travis-app. But you can change node-travis-app with your preferred application name.

heroku create node-travis-app
Creating an app on Heroku via Heroku CLI (node-travis-app)
Creating an app on Heroku via Heroku CLI (node-travis-app)

5. After creating an app, run the below command to generate an authentication token (auth:token).

Travis CI will use this token to gain access to your Heroku account for deploying your application.

heroku auth:token

Note down the token as you’ll need to create an environment variable for this token later.

Generating authentication token
Generating authentication token

6. Navigate to your build on Travis CI, click on the hamburger button (top-right), and choose the Settings option. Doing so redirects your browser to your build’s Settings page (step eight).

Initializing adding environment variables for builds
Initializing adding environment variables for builds

7. On the settings page, fill in the following under the Environment Variables section:

  • NAME – Name the environment variable as you like. But in this tutorial, the name is set to HEROKU_TOKEN.
  • VALUE – Input the token you noted in step six as the value for this environment variable.
  • Click on Add (right-most) to add the environment token.
Adding environment variable (HEROKU_TOKEN)
Adding environment variable (HEROKU_TOKEN)

Once the variable is added successfully, you’ll see a pop-up, like the one below:

Verifying environment variables for builds
Verifying environment variables for builds

Deploying Build to Heroku

All resources are ready, and you’ve come to the most exciting part, deploying your build to Heroku. Travis CI will rebuild your application and then deploy your application to Heroku.

1. Run the following commands to enable Git to track file changes, and add a commit message.

git add .
git commit -m 'Deploying to heroku' 
Adding commit message
Adding commit message

2. Next, run the git push command below to push the changes to the master branch of your remote Git repository.

git push origin master
Pushing changes to the master branch of the Git repository
Pushing changes to the master branch of the Git repository

Travis CI picks up the changes from Git to deploy your application to Heroku on a successful push.

Once deployed on your build in Travis CI, you’ll have a job log similar to the one below. The output below indicates Travis CI has successfully deployed your application to Heroku.

Verifying successful deployment to Heroku
Verifying successful deployment to Heroku

Check your Build History, and you’ll see an output similar below.

Viewing build history
Viewing build history

3. Finally, visit your app’s URL (https://YOUR_APP/.herokuapp.com) to test if your Node application is working. Replace YOUR_APP with your application’s name.

If all goes well, you’ll see a page where a message says Hello world from Travis. Seeing this page indicates Travis CI has successfully built, and deployed your application on Heroku.

Viewing application in web browser

Conclusion

In this tutorial, you’ve learned how to implement CI/CD with Travis CI. You created a Node application, tested the application with Jest and Super-test. Deployment should be complex, and Travis CI lets you deploy your application and every changes without messing things up.

How else will you be using Travis CI? Maybe configure Travis CI to build, run, and deploy a front-end React application to GitHub pages?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!