103 β€” Building and Testing Code with GitHub Actions

Beginner

Master automated testing in CI/CD pipelines. Build applications, run test suites, generate coverage reports, and use matrix strategies for cross-platform testing.

Learning Objectives

1
Build applications automatically in CI pipelines
2
Run automated test suites on every commit
3
Generate and upload test coverage reports
4
Use matrix builds for multi-version testing
5
Upload and download build artifacts
Step 1

Create a project with tests

Set up a Node.js application with a proper test suite.

Commands to Run

mkdir cicd-testing && cd cicd-testing
npm init -y
npm install --save express
npm install --save-dev jest supertest
cat > app.js << 'EOF'
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.json({ message: 'Hello CI/CD!' });
});

app.get('/health', (req, res) => {
  res.json({ status: 'healthy' });
});

module.exports = app;
EOF
cat > server.js << 'EOF'
const app = require('./app');
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
EOF
cat > app.test.js << 'EOF'
const request = require('supertest');
const app = require('./app');

describe('API Endpoints', () => {
  test('GET / returns message', async () => {
    const response = await request(app).get('/');
    expect(response.status).toBe(200);
    expect(response.body.message).toBe('Hello CI/CD!');
  });

  test('GET /health returns healthy status', async () => {
    const response = await request(app).get('/health');
    expect(response.status).toBe(200);
    expect(response.body.status).toBe('healthy');
  });
});
EOF
npx json -I -f package.json -e 'this.scripts.test="jest"'
npx json -I -f package.json -e 'this.scripts.start="node server.js"'
npm test

What This Does

We create a REST API with two endpoints and comprehensive tests. The app.js exports the Express app separately from server.js, making it testable with supertest.

Expected Outcome

Tests pass successfully. You'll see '2 passed' in the test output. This proves our application works before we automate it in CI.

Pro Tips

  • 1
    Separating app from server allows testing without starting the server
  • 2
    supertest makes HTTP endpoint testing simple
  • 3
    All tests should pass locally before pushing to CI
  • 4
    Use descriptive test names that explain what's being tested
Was this step helpful?

All Steps (0 / 12 completed)