Reputation: 117
I am a beginner in unit tests and I want to test my typescript method onSelect that allow user to select only image, pdf and word files. This is my typescript method :
addedfiles : Array<any> = [];
fileRestrictions: FileRestrictions = {
allowedExtensions: ['.jpg', '.png', '.jpeg', '.doc', '.docx','.pdf'],
maxFileSize: 5000000
};
public onSelect(ev: any): void {
ev.files.forEach((file: FileInfo) => {
if (file.rawFile) {
const reader = new FileReader();
if(this.fileRestrictions.allowedExtensions.includes(file.extension.toLowerCase()))
{reader.onloadend = () => {
this.addedfiles.push({ ...file, src: reader.result as string });
};
reader.readAsDataURL(file.rawFile);
console.log(this.addedfiles)
}
}
});
}
I want to write a unit test that test if this method allow users to select png files. So I create this unit test :
it('should select a png file', () => {
const ev = { prevented : false , files : [{uid : '01', name : 'filename', extension : 'png'
, size : 123000 }]};
component.onSelect(ev);
expect(component.addedfiles.length).toEqual(1);
} )
It gives me the Error : Expected 0 to equal 1
! Can anyone help me please ?
Upvotes: 0
Views: 1960
Reputation: 102467
Since reader.onloadend = () => {...}
is a private function, so it's untestable.
You'd better use reader.addEventListener('loadend', () => {...})
. So we can mock addEventListener
method.
Besides, Array.prototype.includes() is an exact match, your test data extension: 'png'
should be extension: '.png'
. And, your test data misses rawFile
property.
A working example using angular
v11+:
example.component.ts
:
import { Component } from '@angular/core';
type FileRestrictions = any;
type FileInfo = any;
@Component({})
export class ExampleComponent {
addedfiles: Array<any> = [];
fileRestrictions: FileRestrictions = {
allowedExtensions: ['.jpg', '.png', '.jpeg', '.doc', '.docx', '.pdf'],
maxFileSize: 5000000,
};
public onSelect(ev: any): void {
ev.files.forEach((file: FileInfo) => {
if (file.rawFile) {
const reader = new FileReader();
if (
this.fileRestrictions.allowedExtensions.includes(
file.extension.toLowerCase()
)
) {
console.log(reader);
reader.addEventListener('loadend', () => {
this.addedfiles.push({ ...file, src: reader.result as string });
});
reader.readAsDataURL(file.rawFile);
console.log(this.addedfiles);
}
}
});
}
}
example.component.spec.ts
:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ExampleComponent } from './example.component';
fdescribe('65356063', () => {
let fixture: ComponentFixture<ExampleComponent>;
let component: ExampleComponent;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [ExampleComponent],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
});
})
);
it('should select a png file', () => {
const ev = {
prevented: false,
files: [
{
uid: '01',
name: 'filename',
extension: '.png',
size: 123000,
rawFile: 'test raw file',
},
],
};
const mockReader = {
addEventListener: jasmine.createSpy().and.callFake((event, listener) => {
listener();
}),
readAsDataURL: jasmine.createSpy(),
};
spyOn(window, 'FileReader').and.returnValue(
(mockReader as unknown) as FileReader
);
component.onSelect(ev);
expect(component.addedfiles.length).toEqual(1);
expect(mockReader.addEventListener).toHaveBeenCalledOnceWith(
'loadend',
jasmine.any(Function)
);
expect(mockReader.readAsDataURL).toHaveBeenCalledOnceWith('test raw file');
});
});
test result:
Upvotes: 1