title: Unit testing for Angular service method with imported third party dependancy
body: <p>I have an Angular service which imports a third party dependancy.  I call the dependancy to give me the browser fingerprint which is then stored in the service.</p>
  
  <p>I am not sure how to mock this dependency in the test so I can assert it has been called and mock a return value.</p>
  
  <p>This is the service:</p>
  
  <pre><code>import { Inject, Injectable } from '@angular/core';
  import * as Fingerprint2 from 'fingerprintjs2';
  
  @Injectable()
  export class ClientInfoService {
      public fingerprint: string | null = null;
  
      constructor() {
      }
  
      createFingerprint(): any {
          return new Fingerprint2();
      }
  
      setFingerprint(): void {
          let fprint = this.createFingerprint();
          setTimeout(() =&gt; fprint.get(hash =&gt; this.fingerprint = hash), 500);
      }
  
      getFingerprint(): string | null {
          return this.fingerprint;
      }
  
  }
  </code></pre>
  
  <p>This is the current test code:</p>
  
  <pre><code>import { TestBed } from '@angular/core/testing';
  import { ClientInfoService } from './client-info.service';
  
  describe('Client Info Service', () =&gt; {
      const hash = 'a6e5b498951af7c3033d0c7580ec5fc6';
      let service: ClientInfoService;
  
      beforeEach(() =&gt; {
          TestBed.configureTestingModule({
              providers: [ClientInfoService],
          });
          service = TestBed.get(ClientInfoService);
      });
  
      test('should be defined', () =&gt; {
          expect(service).toBeDefined();
      });
  
  
      describe('get the fingerprint', () =&gt; {
  
          test('it should be null', () =&gt; {
              let fprint = service.getFingerprint();
              expect(fprint).toBeNull();
          });
  
          test('it should be the hash value', () =&gt; {
              service.fingerprint = hash;
              let fprint = service.getFingerprint();
              expect(fprint).toEqual(hash);
          });
  
      test('it should get the hash value after setting', () =&gt; {
          jest.useFakeTimers();
          service.createFingerprint = jest.fn().mockReturnValue(() =&gt; {
              return {
                  get: function (cb) {
                      return cb(hash);
                  }
              };
          });
          spyOn(service, 'createFingerprint');
          service.setFingerprint();
          jest.runAllTimers();
          expect(service.createFingerprint).toHaveBeenCalled();
          expect(service.fingerprint).toEqual(hash);
      });
  
      });
  
  });
  </code></pre>