DEV Community

Fran Saoco
Fran Saoco

Posted on

3 1 1 1

Using and Mocking Angular Environments with Jest

In production-grade Angular applications, API URLs and other environment-specific properties are typically configured through environment files located in the src/environments/ directory. These can be generated using the Angular CLI command:

ng generate environments
Enter fullscreen mode Exit fullscreen mode

This creates the standard environment files:

  • environment.ts (production defaults)
  • environment.development.ts (development configuration)
  • You could add other environments like staging...

Secure Configuration Management

For security best practices:

  • Never commit sensitive URLs directly in environment files
  • Use CI/CD variables (GitLab, GitHub Actions, etc.) to inject values during build

Protect repository variables by marking them as:

  • Masked (hidden in logs)
  • Protected (only available on protected branches)

Update the files:
environment.ts

export const environment = {
    production: true,
    API_URL: '${API_URL}' // CI/CD variable - This will be replaced during build
};
Enter fullscreen mode Exit fullscreen mode

environment.development.ts

export const environment = {
  production: false,
  API_URL: 'https://api.example.com/data' // Used only in development
};
Enter fullscreen mode Exit fullscreen mode

Use the environment variables:
data-http.service.ts

...
import { environment } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class DataHttpService {
  http = inject(HttpClient);

  getData(): Observable<unknown> {
    return this.http.get<unknown>(environment.API_URL);
  }
}
Enter fullscreen mode Exit fullscreen mode

Unit testing with environment mocks

You could add an environment global mock in setup-jest.ts:

...

jest.mock('./src/environments/environment', () => ({
  environment: {
    API_URL: 'https://api.example.com/data',
    production: false
  }
}));
Enter fullscreen mode Exit fullscreen mode

Mocking environment variables in unit tests is strongly recommended to ensure isolation, consistency, and security while testing all scenarios.

data-http.service.spec.ts

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { DataHttpService } from './data-http.service';
import { environment } from '../environments/environment';


describe('DataHttpService', () => {
  let service: DataHttpService;
  let httpMock: HttpTestingController;
  const mockData = { id: 1, name: 'Test Data' };

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [DataHttpService]
    });

    service = TestBed.inject(DataHttpService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();  // Verify no outstanding requests
  });

  it('should use mock API_URL', () => {
    expect(environment.API_URL).toBe('https://api.example.com/data'); // Url defined in the setup-jest.ts file
  });

  describe('.getData', () => {
        it('should make GET request and return data', () => {
        service.getData().subscribe(data => {
          expect(data).toEqual(mockData);
        });

        const req = httpMock.expectOne(environment.API_URL);
        expect(req.request.method).toEqual('GET');
        req.flush(mockData);
      });
    });
});
Enter fullscreen mode Exit fullscreen mode

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video 🎥

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay