title: Angular - unit test spy are not recognising that the function has been called
body: <p>I've got a test component that I use for testing directives:</p>
  
  <pre><code>export class UnitTestComponent implements OnInit {
    @ViewChild(BackgroundLoadedDirective) backgroundLoaded: BackgroundLoadedDirective;
  
    public url = 'https://www.codeproject.com/KB/GDI-plus/ImageProcessing2/flip.jpg';
  
    constructor() {}
  
    ngOnInit() {}
  
    loaded(): void {
      console.log(true)
    }
  }
  </code></pre>
  
  <p>Then I have this directive which I would like to write some tests for:</p>
  
  <pre><code>@Directive({
    selector: '[backgroundLoaded]'
  })
  
  export class BackgroundLoadedDirective {
    @Input('backgroundLoaded') set url(value) {
      this.createImage(value);
    };
  
    get url() {
      return this._url;
    }
  
    @Output() loaded: EventEmitter&lt;any&gt; = new EventEmitter&lt;any&gt;();
  
    public img: HTMLImageElement;
  
    private _url: string;
  
    @HostBinding('class.background-loaded')
    isLoaded = false;
  
    createImage(url: string): void {
  
      // This gets logged as expected
      console.log(url);
  
      this._url = url;
  
      this.img = new Image();
  
      this.img.onload = () =&gt; {
        this.isLoaded = true;
        this.load.emit(url);
      };
  
      this.img.src = url;
    }
  }
  </code></pre>
  
  <p>Then I have just this test so far:</p>
  
  <pre><code>describe('BackgroundLoadedDirective', () =&gt; {
  
    let component: UnitTestComponent;
    let fixture: ComponentFixture&lt;UnitTestComponent&gt;;
    let spy: any;
  
    beforeEach(() =&gt; {
  
      TestBed.configureTestingModule({
        declarations: [
          UnitTestComponent,
          BackgroundLoadedDirective
        ],
        schemas: [NO_ERRORS_SCHEMA],
        providers: [
          {provide: ComponentFixtureAutoDetect, useValue: true}
        ]
      });
  
      fixture = TestBed.createComponent(UnitTestComponent);
      component = fixture.componentInstance;
    });
  
    it('should create a fake img tag', () =&gt; {
  
      spy = spyOn(component.backgroundLoaded, 'createImage').and.callThrough();
  
      expect(component.backgroundLoaded.img).toBeTruthy();
      expect(spy).toHaveBeenCalled();
    });
  });
  </code></pre>
  
  <p>The problem is that the test fails saying:</p>
  
  <pre><code>Expected spy createImage to have been called.
  </code></pre>
  
  <p>Why isn't the spy working despite the function being called?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Just to clarify, this is the test component's html which applies the directive and gives it the url.</p>
  
  <pre><code>&lt;div [urlToBackground]="url" [backgroundLoaded]="url" (loaded)="loaded($event)"&gt;&lt;/div&gt;
  </code></pre>