> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Run and Test NodeJS App on Local Machine

> Learn to run and test the Solar System Node.js application locally before integrating it into a GitLab CI/CD pipeline.

Learn how to run and test the Solar System Node.js application locally before integrating it into a GitLab CI/CD pipeline. The source code is hosted on GitLab.

<Frame>
  ![The image shows a GitLab repository page for a project named "Solar-System," displaying the project files and their last commit details. The interface includes options for managing, planning, and deploying the project.](https://kodekloud.com/kk-media/image/upload/v1752877290/notes-assets/images/GitLab-CICD-Architecting-Deploying-and-Optimizing-Pipelines-Run-and-Test-NodeJS-App-on-Local-Machine/gitlab-solar-system-repo-page.jpg)
</Frame>

## Prerequisites

* Node.js and npm
* A running MongoDB instance or Atlas cluster
* Git installed on your machine

To verify Node.js and npm:

```bash theme={null}
node --version   # e.g., v18.x.x
npm --version    # e.g., 9.x.x
```

## Clone the Repository

```bash theme={null}
git clone https://gitlab.com/sidd-harth/solar-system.git
cd solar-system
```

## Project Structure and Key Files

This repository includes:

* **package.json**: Defines metadata, scripts, dependencies, and coverage thresholds
* **app.js**: Backend Express.js server
* **client.js**: Frontend script to fetch planet data
* **Dockerfile**: Build instructions for a Docker image
* **deployment.yaml** & **service.yaml**: Kubernetes manifests

### package.json

```json theme={null}
{
  "name": "Solar System",
  "version": "6.7.6",
  "author": "Siddharth Barahalikar",
  "license": "MIT",
  "scripts": {
    "start": "node app.js",
    "test": "mocha app-test.js --timeout 10000 --reporter mocha-junit-reporter --exit",
    "coverage": "nyc --reporter cobertura --reporter lcov --reporter text --reporter json-summary mocha app-test.js"
  },
  "nyc": {
    "check-coverage": true,
    "lines": 90
  },
  ...
}
```

| Script   | Description                                 | Command            |
| -------- | ------------------------------------------- | ------------------ |
| start    | Launch the Express server                   | `npm start`        |
| test     | Run tests with Mocha and JUnit reporter     | `npm test`         |
| coverage | Generate coverage reports (cobertura, lcov) | `npm run coverage` |

### Application Backend (app.js)

```javascript theme={null}
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

const app = express();
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '/')));
app.use(cors());

mongoose.connect(process.env.MONGO_URI, {
  user: process.env.MONGO_USERNAME,
  pass: process.env.MONGO_PASSWORD,
  useNewUrlParser: true,
  useUnifiedTopology: true
}, (err) => {
  if (err) {
    console.error("Connection error:", err);
  } else {
    console.log("Connected to MongoDB");
  }
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});
```

<Callout icon="lightbulb" color="#1CB2FE">
  Ensure you add your REST API route handlers in `app.js` (for example, a GET `/os` endpoint) before testing.
</Callout>

### Frontend Controller (client.js)

```javascript theme={null}
console.log('Client script loaded');

window.onload = () => {
  console.log("Requesting all planets");
  fetch("/os", { method: "GET" })
    .then(res => res.ok ? res.json() : Promise.reject("Fetch error"))
    .then(data => console.log(data))
    .catch(error => console.error(error));
};
```

### Dockerfile

```dockerfile theme={null}
FROM node:18-alpine3.17
WORKDIR /usr/app
COPY package*.json ./
RUN npm install
COPY . .
ENV MONGO_URI=uriPlaceholder
ENV MONGO_USERNAME=usernamePlaceholder
ENV MONGO_PASSWORD=passwordPlaceholder
EXPOSE 3000
CMD ["npm", "start"]
```

### Kubernetes Manifests

```yaml theme={null}
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: solar-system
  labels:
    app: solar-system
spec:
  replicas: 2
  selector:
    matchLabels:
      app: solar-system
  template:
    metadata:
      labels:
        app: solar-system
    spec:
      containers:
        - name: solar-system
          image: your-repo/solar-system:latest
          ports:
            - containerPort: 3000
---
# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: solar-system
  labels:
    app: solar-system
spec:
  type: NodePort
  selector:
    app: solar-system
  ports:
    - port: 3000
      targetPort: 3000
      protocol: TCP
```

| Resource Type | Purpose                          | Example                      |
| ------------- | -------------------------------- | ---------------------------- |
| Deployment    | Manages pods and rolling updates | Defined in `deployment.yaml` |
| Service       | Exposes pods on the network      | Defined in `service.yaml`    |

## Install Dependencies

```bash theme={null}
npm install
```

You may see notices:

```plaintext theme={null}
44 packages are looking for funding
Run `npm fund` for details

1 high severity vulnerability
To address all issues, run:
  npm audit fix
```

## Running the Server Locally

After dependencies are installed:

```bash theme={null}
npm start
```

Open [http://localhost:3000](http://localhost:3000) in your browser:

<Frame>
  ![The image shows a digital illustration of the solar system with planets orbiting the sun, accompanied by a user interface for searching planets. The background is a starry space theme with text describing the solar system.](https://kodekloud.com/kk-media/image/upload/v1752877291/notes-assets/images/GitLab-CICD-Architecting-Deploying-and-Optimizing-Pipelines-Run-and-Test-NodeJS-App-on-Local-Machine/solar-system-planets-ui-illustration.jpg)
</Frame>

You can search by ID (e.g., 3 for Earth, 6 for Saturn). Data is fetched from your MongoDB.

<Frame>
  ![The image shows a webpage about the solar system, specifically focusing on Saturn, with a stylized illustration of the planet and its rings on a starry background. There is a description of Saturn and a search feature for exploring planets.](https://kodekloud.com/kk-media/image/upload/v1752877292/notes-assets/images/GitLab-CICD-Architecting-Deploying-and-Optimizing-Pipelines-Run-and-Test-NodeJS-App-on-Local-Machine/saturn-solar-system-webpage-illustration.jpg)
</Frame>

## Testing the Application

Run the test suite:

```bash theme={null}
npm test
```

If environment variables are missing, you will see:

```plaintext theme={null}
MongooseError: The `uri` parameter to `openUri()` must be a string, got `undefined`.
```

<Callout icon="triangle-alert" color="#FF6B6B">
  Tests will fail without `MONGO_URI`, `MONGO_USERNAME`, and `MONGO_PASSWORD`. Set these before running `npm test`.
</Callout>

### Temporary Local Credentials

For a quick local demo, hard-code your MongoDB URI in `app.js`:

```javascript theme={null}
mongoose.connect('mongodb+srv://supercluster.d83jj.mongodb.net/superData', {
  user: 'superuser',
  pass: 'SuperPassword',
  useNewUrlParser: true,
  useUnifiedTopology: true
}, (err) => {
  if (err) console.error("Connection error:", err);
});
```

Re-run tests:

```bash theme={null}
npm test
echo $?   # 0 means success
```

A `test_results.xml` file is generated for CI/CD:

```xml theme={null}
<?xml version="1.0" encoding="UTF-8"?>
<testsuites name="Mocha Tests" time="3.953" tests="11" failures="0">
  <testsuite name="Planets API Suite" tests="8" time="3.953">
    <testcase name="Fetching Planet Details - Mercury" time="2.350" />
    <testcase name="Fetching Planet Details - Venus" time="0.224" />
    <!-- more testcases -->
  </testsuite>
</testsuites>
```

## Coverage Report

Generate coverage:

```bash theme={null}
npm run coverage
```

```plaintext theme={null}
11 passing (4s)
ERROR: Coverage for lines (88.88%) does not meet global threshold (90%)
```

A non-zero exit code will signal coverage failures in CI pipelines.

## Links and References

* [Node.js](https://nodejs.org/)
* [npm](https://www.npmjs.com/)
* [Express Documentation](https://expressjs.com/)
* [Mongoose Documentation](https://mongoosejs.com/)
* [Mocha](https://mochajs.org/)
* [nyc (Istanbul)](https://github.com/istanbuljs/nyc)
* [Docker Hub](https://hub.docker.com/)
* [Kubernetes Basics](https://kubernetes.io/docs/concepts/overview/what-is-kubernetes/)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/gitlab-ci-cd-architecting-deploying-and-optimizing-pipelines/module/3a1c2306-8091-4dfe-b40f-e2ca53918553/lesson/f6de778b-f061-4043-92ad-dc97d2eee6c7" />
</CardGroup>
