I'm (very) new to writing unit tests and I'm wondering how I should approach testing a static method that constructs our API endpoints based on what the properties are set to in our environment.ts file.

The environment.ts file changes with the environment, so I'm curious how I would accommodate for that in my test.

Does my method need to be refactored to make this easier to test? For example, instead of implicitly referencing environment.endpoint, instead pass-in environment as a argument? Would I mock the environment.ts file?

Any suggestions would be helpful.

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

export class Utilities {

  public static constructAPIEndpoint(): string {
    const hostname: string = environment.endpoint;
    const protocol: string = environment.local ? 'http:' : 'https:';

    return `${protocol}//${hostname}/`;


export const environment = {
  production: false,
  local: false,
  hostname: 'localhost',
  showLogs: true,
  endpoint: 'foo-dev-graphapp.com',
  appInsights: {
    instrumentationKey: '123'

jasmine test:

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

  it('constructAPIEndpoint() it should construct an endpoint based on environment.ts', () => {
    const endpoint: string = Utilities.constructAPIEndpoint();

    /// THIS DOESN'T SEEM - having to recreate logic inside constructAPIEndpoint()
    const protocol: string = environment.local ? 'http:' : 'https';



1 Answer 1


If you really want to unit test that logic, you should fake its data. In order to do that, you need a way to inject that dependency instead of getting it straight from it.

You have 3 options:

  1. Installing a framework to mock the import (as detailed in https://medium.com/@emandm/import-mocking-with-typescript-3224804bb614)
  2. Have a constructor that is autocalled for its usage statically.
  3. Similar to number 2: have a method with environment as parameter (so you can test it), and the current one calls the new one with the imported environment as parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.