1
\$\begingroup\$

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}/`;
 }
}

environments.ts

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';
 expect(endpoint).toEqual(`${protocol}//${environment.endpoint}`);
 });
asked Jan 24, 2019 at 21:34
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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.
answered May 21, 2019 at 21:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.