Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Unit testing spy not called

I am testing a component say : export and import files which uses a service called uploadService.ts

uploadService has a method sendFile which is called internally by component method importRules().

uploadService.ts

@Injectable()
export class UploadService {

    constructor(private http: Http, private sharedData: SharedDataService) { }

    sendFile(file: File, groupName?: string): Observable<Response> {
        …
        return this.http.post(url, data, options);
    }
}

exportImport.components.ts

ImportRules() {
     this.uploadService.sendFile(fileObj, fileName) {
     …
     }
}

Corresponding spec file exportImport.components.spec.ts

class MockUploadService extends UploadService {
            constructor() {
                super(null, null);
            }

            sendFile(file: File, groupName?: string): Observable<Response> {
                let resObject = new Response(null);
                resObject.status = 200;
                return Observable.of(resObject);
            }
        }

And in beforeEach I have replaced real service with mock service

it('should import ioc rules',
        async(() => {
            TestBed
                .compileComponents()
                .then(() => {
                    let fixture = TestBed.createComponent(TestComponent);
                    // let http = new ConnectionBackend();
                    let exportImportInstance = fixture.debugElement.children[0].componentInstance;
                    let mockReq: MockUploadService = new MockUploadService();
                    exportImportInstance.setGroupName('test');
                    exportImportInstance.setChosenFile('file.json');
                    spyOn(mockReq, 'sendFile');
                    exportImportInstance.importRules();
                    expect(mockReq.sendFile).toHaveBeenCalledWith('file.json', 'test');
                });

        }));

But on executing the test I am getting error:

Expected spy sendFile to have been called with [ 'file.json', 'test' ] but it was never called.

I am not getting what I am doing wrong here.

like image 508
nikhil Avatar asked Jun 13 '26 09:06

nikhil


1 Answers

Use spyOn in following way :

let fixture = TestBed.createComponent(TestComponent);
const mockResponse = { 'name': 'uploaded' };
let spy: jasmine.Spy = spyOn(mockUploadService,'sendFile').and.returnValue(Observable.of(
                        new Response(new ResponseOptions({ body: mockResponse }))));
expect(spy.calls.any()).toBe(true, 'spy send file of upload is called');
expect(spy.calls.first().args[0]).toBe('file.json');
like image 166
Ruchi Wadhwa Avatar answered Jun 16 '26 10:06

Ruchi Wadhwa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!