Reputation: 28368
I've got a test component that I use for testing directives:
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)
}
}
Then I have this directive which I would like to write some tests for:
@Directive({
selector: '[backgroundLoaded]'
})
export class BackgroundLoadedDirective {
@Input('backgroundLoaded') set url(value) {
this.createImage(value);
};
get url() {
return this._url;
}
@Output() loaded: EventEmitter<any> = new EventEmitter<any>();
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 = () => {
this.isLoaded = true;
this.load.emit(url);
};
this.img.src = url;
}
}
Then I have just this test so far:
describe('BackgroundLoadedDirective', () => {
let component: UnitTestComponent;
let fixture: ComponentFixture<UnitTestComponent>;
let spy: any;
beforeEach(() => {
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', () => {
spy = spyOn(component.backgroundLoaded, 'createImage').and.callThrough();
expect(component.backgroundLoaded.img).toBeTruthy();
expect(spy).toHaveBeenCalled();
});
});
The problem is that the test fails saying:
Expected spy createImage to have been called.
Why isn't the spy working despite the function being called?
EDIT:
Just to clarify, this is the test component's html which applies the directive and gives it the url.
<div [urlToBackground]="url" [backgroundLoaded]="url" (loaded)="loaded($event)"></div>
Upvotes: 2
Views: 2716
Reputation: 8165
Basically what's interfering are angulars lifecycle hooks. Your test just doesn't cares enough in terms of timing.
To make it easier to test, trigger a change and then test if your setter works (and calls the function you're spying on).
Something like this:
it('should create a fake img tag', () => {
let spy: jasmine.Spy = spyOn(component.backgroundLoaded, 'createImage').and.callThrough();
comp.backgroundLoaded.url = 'foobar';
fixture.detectChanges(); // wait for the change detection to kick in
expect(spy).toHaveBeenCalled();
});
Hope it helps.
(edit: removed one detectChanges()
for ngOnInit
, because it's not needed here and should be called before the test anyway)
Upvotes: 3