Faking a library in unit testing


#1

I have a function in ionic 2 service which I would like to test.

service.ts

upload(){
  let file = new Transfer();
  file.upload(myfile).then( // my callback );
}

I would like to mock Transfer in my test using jasmine. I tried this in my

sevice.spec.ts

import { TransferMock as Transfer } from '../mocks/mocks' to mock it. But it is not working. This is how my test is instantiated .

describe('authentication service' , () => {
  beforeEach(() => {
    auth = new Service(<any>new HttpMock(), <any>new StorageMock())
  });
  it('initialize authentication',() => {
    expect(auth).not.toEqual(null);
  });
})

Transfer is not injected in the service.


#2

you should read about testing in angular 2

There is a class called testbed where you can override providers.

For libs:

  • create a mock that implements the api of the lib
  • use spyOn to avoid calling the original methods and return a mocked value.

#3

I can mock providers the way you mentioned. But as I mentioned in my question , this is not an injected provider. I know how it could have been done if it was Transfer.upload.

spyOn(Transfer,'upload').and.

But in my case it is
let file = new Transfer() file.upload()
I am not sure how to do this when its constructor.